1
votes

I have created on JS SPA which calls Web API. I am using CORS to allow all request for Web Api using tag "assembly: OwinStartup" and "app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);"

Complete application here

For Edge request is successful whereas in Chrome it is not. I am getting error: 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.

Interesting part is I am unable to see any "Access-Control-Allow-Origin" request header for both in Developer tool.

For Chrome:

:authority:localhost:44373 :method:GET :path:/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, like Gecko) Chrome/63.0.3239.108 Safari/537.36

For Edge:

Accept: 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, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393 X-P2P-PeerDist: Version=1.1 X-P2P-PeerDistEx: MinContentInformation=1.0, MaxContentInformation=2.0

My start up page looks like this

2

2 Answers

0
votes

My guess for it "working" in Edge is because it's detected localhost and decided not to do a CORS check; but Chrome will always do the check.

Anyways, you're not seeing the header because its not there. To get it working, do the following:

Add these 2 packages: Microsoft.AspNet.WebApi.Owin and Microsoft.Owin.Host.SystemWeb

Comment out GlobalConfiguration.Configure(WebApiConfig.Register); from the global.asax file because we want to use OWIN for Web API.

Replace Configuration() with this code in your 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
votes

You have to use this line of code as the first statement in the startup class --

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