Enable OWIN Cross-origin Request

时间:2023-03-09 04:04:02
Enable OWIN Cross-origin Request

微软出了一套解决方式能够解决 “同意WebAPI的 CORS 请求”

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

假设你同一时候使用了OWIN,即使使用了这个,也不能使OWIN 同意 cross-origin 请求。

OWIN 是基于kantana的一套OAUTH2.0解决方式。

所以要使用 DLL Microsoft.OWIN.Cros

I installed Microsoft.Owin.Cors package
on the API Server. In Startup.Auth.cs file,
under public
void ConfigureAuth(IAppBuilder app)
, I added in

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

In WebApiConfig.cs,
under public
static void Register(HttpConfiguration config)
, I added in these lines:

// Cors
var cors = new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS");
config.EnableCors(cors);

须要注意的是:

app.UseCors(CorsOptions.AllowAll)
- enables CORS for all
cross-origins
requests to your site.

config.EnableCors(..)
enables CORS for Web Api only

意思就是:

假设你使用了Microsoft.Owin.Cors,然后在Startup.Auth.cs中加上了app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

就不须要再用config.EnableCors(..)
了。

或者 最直接的方法()!!!!

<httpProtocol>

      <customHeaders>

        <add name="Access-Control-Allow-Origin" value="*" />

        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />

      </customHeaders>

  </httpProtocol>

把这段加在web.config的<system.webServer>节点下,成功!