Microsoft Owin Cors allow all not working in Chrome for Web API

Microsoft Owin Cors allow all not working in Chrome for Web API

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

完成申请here

对于 Edge 请求成功,而在 Chrome 中则不成功。我收到错误消息:无法加载 https://localhost:44373/api/location?cityName=dc: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44392' 因此不允许访问。

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

对于Chrome:

:权限:localhost:44373 :方法:获取 :path:/api/location?cityName=dc :方案:https 接受: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 来源:https://localhost:44392 pragma:no-缓存 推荐人:https://localhost:44392/ user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36

对于边缘:

接受:application/json、text/plain、/ Accept-Encoding: gzip, deflate, peerdist Accept-Language: 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, like 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

你必须使用这行代码作为启动中的第一条语句class --

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

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

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

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

global.asax 文件中注释掉 GlobalConfiguration.Configure(WebApiConfig.Register);,因为我们想使用 OWIN for 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);
}