MVC的Web API:没有“访问控制允许来源”标头的请求的资源present [英] MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

查看:491
本文介绍了MVC的Web API:没有“访问控制允许来源”标头的请求的资源present的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,写这篇文章中的所有内容:<一href=\"http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api\">http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api,但没有任何工程。
我试图从webAPI2(MVC5)获取数据使用angularJS在其他领域使用。

我的控制器是这样的:

 命名空间tapuzWebAPI.Controllers
{
    [EnableCors(来源:http://local.tapuz.co.il,标题:*,方法:*,SupportsCredentials = TRUE)]
    [途径preFIX(API /主页)]
    公共类HomePageController:ApiController
    {
        [HTTPGET]
        〔路线(GetMainItems)]
        // [responseTyp的(typeof运算(产品))]
        公开名单&LT; usp_MobileSelectTopSecondaryItemsByCategoryResult&GT; GetMainItems()
        {
            HomePageDALcs DAL =新HomePageDALcs();
            //三个产品加入到显示数据            //HomePagePromotedItems.Value.Add(new HomePagePromotedItem.Value.FirstOrDefault((P)=&GT; p.ID == ID));
            清单&LT; usp_MobileSelectTopSecondaryItemsByCategoryResult&GT;项= dal.MobileSelectTopSecondaryItemsByCategory(3,5);
            返回的物品;        }
    }
}


解决方案

您需要启用的 CORS 网页API 。更容易和preferred方法,使全球CORS是添加以下到的web.config

 &LT; system.webServer&GT;
  &LT; httpProtocol&GT;
    &LT; customHeaders&GT;
      &LT;添加名称=访问控制允许来源VALUE =*/&GT;
      &LT;添加名称=访问控制 - 允许 - 头VALUE =Content-Type的/&GT;
      &LT;添加名称=访问控制允许的方法VALUE =GET,POST,PUT,DELETE,OPTIONS/&GT;
    &LT; / customHeaders&GT;
  &LT; / httpProtocol&GT;
&LT; /system.webServer>

请注意,方法的都是单独指定,而不是使用 * 。这是因为没有使用 *

当发生错误

您还可以启用的 CORS 的由code。

更新结果
下面的的NuGet 的要求软件包: Microsoft.AspNet.WebApi.Cors

 公共静态类WebApiConfig
{
    公共静态无效的注册(HttpConfiguration配置)
    {
        config.EnableCors();        // ...
    }
}

然后你可以使用动作和控制器这样的 [EnableCors] 属性

  [EnableCors(来源:http://www.example.com,标题:*,方法:*)]

或者你也可以在全球进行注册。

 公共静态类WebApiConfig
{
    公共静态无效的注册(HttpConfiguration配置)
    {
        变种CORS =新EnableCorsAttribute(http://www.example.com,*,*);
        config.EnableCors(CORS);        // ...
    }
}

您还需要处理preflight 选项请求的有 HTTP选项请求。

的Web API 需要的选项请求进行响应,以确认它确实配置为支持 CORS

要解决这个问题,所有你需要做的就是发送的空响应的后面。你可以这样做你的行动里面,或者你可以做到这一点全球是这样的:

 #的Global.asax.cs
保护无效的Application_BeginRequest()
{
    如果(Request.Headers.AllKeys.Contains(起源)及和放大器; Request.HttpMethod ==选项。)
    {
        Response.Flush();
    }
}

加入这个额外的检查,以确保老的API 是被设计为只接受 GET POST 请求将不会被利用。想象一下,发送删除请求到 API 这个时候的动词的不存在而设计的。其结果是未predictable 的,其结果可能是的危险

I tried everything that is written in this article: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api, but nothing works. I'm trying to get data from webAPI2 (MVC5) to use in another domain using angularJS.

my controller looks like this:

namespace tapuzWebAPI.Controllers
{
    [EnableCors(origins: "http://local.tapuz.co.il", headers: "*", methods: "*", SupportsCredentials = true)]
    [RoutePrefix("api/homepage")]
    public class HomePageController : ApiController
    {
        [HttpGet]
        [Route("GetMainItems")]
        //[ResponseType(typeof(Product))]
        public List<usp_MobileSelectTopSecondaryItemsByCategoryResult> GetMainItems()
        {


            HomePageDALcs dal = new HomePageDALcs();
            //Three product added to display the data

            //HomePagePromotedItems.Value.Add(new HomePagePromotedItem.Value.FirstOrDefault((p) => p.ID == id));


            List<usp_MobileSelectTopSecondaryItemsByCategoryResult> items = dal.MobileSelectTopSecondaryItemsByCategory(3, 5);
            return items;

        }      
    }
}

解决方案

You need to enable CORS in your Web Api. The easier and preferred way to enable CORS globally is to add the following into web.config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

Please note that the Methods are all individually specified, instead of using *. This is because there is a bug occurring when using *.

You can also enable CORS by code.

Update
The following NuGet package is required: Microsoft.AspNet.WebApi.Cors.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        // ...
    }
}

Then you can use the [EnableCors] attribute on Actions or Controllers like this

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]

Or you can register it globally

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
        config.EnableCors(cors);

        // ...
    }
}

You also need to handle the preflight Options requests with HTTP OPTIONS requests.

Web API needs to respond to the Options request in order to confirm that it is indeed configured to support CORS.

To handle this, all you need to do is send an empty response back. You can do this inside your actions, or you can do it globally like this:

# Global.asax.cs
protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

This extra check was added to ensure that old APIs that were designed to accept only GET and POST requests will not be exploited. Imagine sending a DELETE request to an API designed when this verb didn't exist. The outcome is unpredictable and the results might be dangerous.

这篇关于MVC的Web API:没有“访问控制允许来源”标头的请求的资源present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆