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

问题描述 投票:1回答:2

我在JS SPA上创建了一个调用Web API的程序。我正在使用CORS来使用标签“assembly:OwinStartup”和“app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);”允许所有Web Api请求。

完整的申请here

对于Edge请求是成功的而在Chrome中则不是。我收到错误:无法加载https://localhost:44373/api/location?cityName=dc:请求的资源上没有“Access-Control-Allow-Origin”标头。因此,'https://localhost:44392'原产地不允许进入。

有趣的是,我无法在Developer工具中看到任何“Access-Control-Allow-Origin”请求标头。

对于Chrome:

:authority:localhost:44373:方法:GET:路径:/ api / location?cityName = dc:scheme:https accept:application / json,text / plain,/ accept-encoding:gzip,deflate,br accept-language:en -US,en; q = 0.9,bn; q = 0.8 cache-control:no-cache origin:https://localhost:44392 pragma:no-cache referer: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

对于Edge:

接受:application / json,text / plain,/ Accept-Encoding:gzip,deflate,peerdist Accept-Language:en-US Host:localhost:44373 Origin:https://localhost:44392 Referer: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

javascript asp.net-web-api cors owin
2个回答
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);
}

1
投票

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

 public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
...
...
...
© www.soinside.com 2019 - 2024. All rights reserved.