一尘不染

Asp.Net WebApi2启用CORS无法与AspNet.WebApi.Cors 5.2.3一起使用

c#

我尝试按照http://enable-cors.org/server_aspnet.html 上的步骤操作,以使我的RESTful API(使用ASP.NET
WebAPI2实现)可以处理跨源请求(启用CORS)。除非我修改web.config,否则它将无法正常工作。

我安装了WebApi Cors依赖项:

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

然后在我App_Start的班级中WebApiConfig,如下所示:

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标头,例如:

  • Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONS
  • Access-Control-Allow-Origin: *

我错过了一步吗?我尝试在控制器上使用以下注释:

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

结果相同,未启用CORS。

但是,如果我在web.config中添加以下内容(甚至不安装AspNet.WebApi.Cors依赖项),则它会起作用:

<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>

任何帮助将非常感激!

谢谢。


阅读 323

收藏
2020-05-19

共1个答案

一尘不染

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

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

[Global.ascx](https://github.com/bigfont/webapi-

cors/blob/master/CORS/Global.asax.cs)

所有这一切都称为WebApiConfig。只是代码组织而已。

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

[WebApiConfig.cs](https://github.com/bigfont/webapi-

cors/blob/master/CORS/App_Start/WebApiConfig.cs)

您这里的关键方法是EnableCrossSiteRequests方法。这就是您需要做的 所有
事情。该EnableCorsAttribute是一个全球范围的CORS属性

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

[价值观控制器](https://github.com/bigfont/webapi-

cors/blob/master/CORS/Controllers/ValuesController.cs)

Get方法接收EnableCors我们全局应用的属性。该Another方法将覆盖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](https://github.com/bigfont/webapi-

cors/blob/master/CORS/Web.config)

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

<?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>
2020-05-19