首页 文章

Microsoft Owin Cors允许所有不在Chrome for Web API中工作

提问于
浏览
1

我在JS SPA上创建了Web API . 我使用CORS允许使用标签“ assembly: OwinStartup " and " app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); ”的所有Web Api请求

完整申请here

对于Edge请求是成功的而在Chrome中则不是 . 我收到错误: Failed to load https://localhost:44373/api/location?cityName=dc: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44392' is therefore not allowed access.

有趣的是,我无法在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

2 回答

  • 1

    我对它的猜测"working"在Edge是因为它被检测到 localhost 并且决定不进行CORS检查;但Chrome将始终进行检查 .

    无论如何,你没有看到 Headers ,因为它不在那里 . 要使其正常工作,请执行以下操作:

    添加这两个包: Microsoft.AspNet.WebApi.OwinMicrosoft.Owin.Host.SystemWeb

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

    StartUp 中的代码替换 Configuration()

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

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

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

相关问题