Microsoft Owin Cors允许所有不能在Chrome for Web API中使用

时间:2017-12-22 06:58:51

标签: javascript asp.net-web-api cors owin

我在JS SPA上创建了一个调用Web API的程序。我正在使用CORS来使用标签" 汇编:OwinStartup "和" app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); "

完整申请here

对于Edge请求是成功的而在Chrome中则不是。我收到错误消息:无法加载https://localhost:44373/api/location?cityName=dc:没有' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' https://localhost:44392'因此不允许访问。

有趣的部分是我无法看到任何" 访问控制 - 允许 - 来源"开发人员工具中的请求标头。

对于Chrome:

:授权:本地主机:44373 :方法:GET :路径:/ API /位置的cityName = DC? :方案:HTTPS 接受:application / json,text / plain, / accept-encoding:gzip,deflate,br 接受语言:EN-US,EN; Q = 0.9,BN; Q = 0.8 缓存控制:无缓存 起源:https://localhost:44392 附注:无缓存 引用者:https://localhost:44392/ user-agent:Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,如Gecko)Chrome / 63.0.3239.108 Safari / 537.36

For Edge:

接受:application / json,text / plain, / Accept-Encoding:gzip,deflate,peerdist 接受语言:en-US 主持人:localhost:44373 来源:https://localhost:44392 推荐人:https://localhost:44392/ User-Agent:Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 51.0.2704.79 Safari / 537.36 Edge / 14.14393 X-P2P-PeerDist:版本= 1.1 X-P2P-PeerDistEx:MinContentInformation = 1.0,MaxContentInformation = 2.0

我的启动页面看起来像this

2 个答案:

答案 0 :(得分:1)

您必须使用此行代码作为启动类中的第一个语句 -

 public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
...
...
...

答案 1 :(得分:0)

我在Edge中“工作”的猜测是因为它检测到 localhost 并决定不进行CORS检查;但Chrome会随时进行检查。

无论如何,你没有看到标题,因为它不存在。要使其正常工作,请执行以下操作:

添加以下两个软件包: Microsoft.AspNet.WebApi.Owin Microsoft.Owin.Host.SystemWeb

GlobalConfiguration.Configure(WebApiConfig.Register);文件中注释掉global.asax,因为我们希望将OWIN用于Web API。

使用Configuration()中的此代码替换StartUp

public void Configuration(IAppBuilder app)
{
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

    HttpConfiguration config = new HttpConfiguration();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    app.UseWebApi(config);
}