Asp.Net WebApi2 启用 CORS 不适用于 AspNet.WebApi.Cors 5.2.3 [英] Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

查看:30
本文介绍了Asp.Net WebApi2 启用 CORS 不适用于 AspNet.WebApi.Cors 5.2.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试按照 http://enable-cors.org/server_aspnet.html 中的步骤操作让我的 RESTful API(使用 ASP.NET WebAPI2 实现)处理跨源请求(启用 CORS).除非我修改 web.config,否则它不起作用.

I tried to follow the steps at http://enable-cors.org/server_aspnet.html to have my RESTful API (implemented with ASP.NET WebAPI2) work with cross origin requests (CORS Enabled). It's not working unless I modify the web.config.

我安装了 WebApi Cors 依赖项:

I installed WebApi Cors dependency:

install-package Microsoft.AspNet.WebApi.Cors -ProjectName MyProject.Web.Api

然后在我的 App_Start 中,我的 WebApiConfig 类如下:

Then in my App_Start I've got the class WebApiConfig as follows:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);

        var constraintsResolver = new DefaultInlineConstraintResolver();

        constraintsResolver.ConstraintMap.Add("apiVersionConstraint", typeof(ApiVersionConstraint));
        config.MapHttpAttributeRoutes(constraintsResolver); 
        config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
        //config.EnableSystemDiagnosticsTracing(); 
        config.Services.Replace(typeof(ITraceWriter), new SimpleTraceWriter(WebContainerManager.Get<ILogManager>())); 
        config.Services.Add(typeof(IExceptionLogger), new SimpleExceptionLogger(WebContainerManager.Get<ILogManager>()));
        config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); 
    }
}

但在我运行应用程序之后,我使用 Fiddler 请求资源,例如:http://localhost:51589/api/v1/persons并且在响应中我看不到我应该看到的 HTTP 标头,例如:

but after that I run the application, I request a resource with Fiddler like: http://localhost:51589/api/v1/persons and in the response I cannot see the HTTP headers that I should see such as:

  • 访问控制允许方法:POST、PUT、DELETE、GET、OPTIONS
  • Access-Control-Allow-Origin: *

我是否遗漏了某些步骤?我尝试在控制器上使用以下注释:

Am I missing some step? I have tried with the following annotation on the controller:

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

相同的结果,没有启用 CORS.

Same result, no CORS enabled.

但是,如果我在 web.config 中添加以下内容(甚至没有安装 AspNet.WebApi.Cors 依赖项),它就可以工作:

However, if I add the following in my web.config (without even installing the AspNet.WebApi.Cors dependency) it works:

<system.webServer>

<httpProtocol>
  <!-- THESE HEADERS ARE IMPORTANT TO WORK WITH CORS -->
  <!--
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
    <add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
  -->
</httpProtocol>
<handlers>
  <!-- THESE HANDLERS ARE IMPORTANT FOR WEB API TO WORK WITH  GET,HEAD,POST,PUT,DELETE and CORS-->
  <!--

  <remove name="WebDAV" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
-->
</handlers>

任何帮助将不胜感激!

谢谢.

推荐答案

我已经为您创建了一个精简的演示项目.

I've created a pared-down demo project for you.

您可以从本地 Fiddler 尝试上述 API 链接以查看标题.这是一个解释.

You can try the above API Link from your local Fiddler to see the headers. Here is an explanation.

所有这些都是调用WebApiConfig.它只不过是代码组织.

All this does is call the WebApiConfig. It's nothing but code organization.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        WebApiConfig.Register(GlobalConfiguration.Configuration);
    }
}

WebApiConfig.cs

此处的关键方法是 EnableCrossSiteRequests 方法.这就是您需要做的全部.EnableCorsAttribute 是一个 全局范围的 CORS 属性.

WebApiConfig.cs

The key method for your here is the EnableCrossSiteRequests method. This is all that you need to do. The EnableCorsAttribute is a globally scoped CORS attribute.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        AddRoutes(config);
    }

    private static void AddRoutes(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/"
        );
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(
            origins: "*", 
            headers: "*", 
            methods: "*");
        config.EnableCors(cors);
    }
}

值控制器

Get 方法接收我们全局应用的 EnableCors 属性.Another 方法覆盖全局 EnableCors.

Values Controller

The Get method receives the EnableCors attribute that we applied globally. The Another method overrides the global EnableCors.

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { 
            "This is a CORS response.", 
            "It works from any origin." 
        };
    }

    // GET api/values/another
    [HttpGet]
    [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
    public IEnumerable<string> Another()
    {
        return new string[] { 
            "This is a CORS response. ", 
            "It works only from two origins: ",
            "1. www.bigfont.ca ",
            "2. the same origin." 
        };
    }
}

Web.config

您无需在 web.config 中添加任何特殊内容.事实上,这就是演示的 web.config 的样子 - 它是空的.

Web.config

You do not need to add anything special into web.config. In fact, this is what the demo's web.config looks like - it's empty.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>

演示

var url = "https://cors-webapi.azurewebsites.net/api/values"

$.get(url, function(data) {
  console.log("We expect this to succeed.");
  console.log(data);
});

var url = "https://cors-webapi.azurewebsites.net/api/values/another"

$.get(url, function(data) {
  console.log(data);
}).fail(function(xhr, status, text) {
  console.log("We expect this to fail.");
  console.log(status);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于Asp.Net WebApi2 启用 CORS 不适用于 AspNet.WebApi.Cors 5.2.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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