MVC web api:请求的资源上不存在“Access-Control-Allow-Origin"标头 [英] MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

查看:40
本文介绍了MVC web api:请求的资源上不存在“Access-Control-Allow-Origin"标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了本文中写的所有内容:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api,但没有任何效果.我正在尝试使用 angularJS 从 webAPI2 (MVC5) 获取数据以在另一个域中使用.

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.

我的控制器如下所示:

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;

        }      
    }
}

推荐答案

您需要在 Web Api 中启用 CORS.全局启用 CORS 的更简单且首选的方法是将以下内容添加到 web.config

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>

请注意方法都是单独指定的,而不是使用*.这是因为使用*时出现了一个bug.

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

您也可以通过代码启用CORS.

You can also enable CORS by code.

更新
需要以下 NuGet 包:Microsoft.AspNet.WebApi.Cors.

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

        // ...
    }
}

然后你可以像这样在动作或控制器上使用 [EnableCors] 属性

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

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

或者你可以全局注册

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

        // ...
    }
}

您还需要处理带有 HTTP OPTIONS 请求的预检Options 请求.

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

Web API 需要响应 Options 请求,以确认它确实配置为支持 CORS.

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();
    }
}

添加此额外检查是为了确保设计为仅接受 GETPOST 请求的旧 API 不会被利用.想象一下,当这个动词不存在时,向一个API发送一个DELETE请求.结果不可预测,结果可能危险.

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:请求的资源上不存在“Access-Control-Allow-Origin"标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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