Question: CORS Error on browser back button


CORS Error on browser back button

Answers 1
Added at 2017-01-01 06:01

I have a ASP.NET Web API 2 Service. And multiple client(angular) applications talks to that service. the applications and the service are published on different sub domains, like the following:

I used Microsoft.AspNet.WebApi.Cors - NuGet package to enable CORS, it is working fine, except for one scenario: When the user opens one application ( Then navigates to another ( Then presses the browser back button. the follwoing CORS Error:

The 'Access-Control-Allow-Origin' header has a value '' that is not equal to the supplied origin. 
Origin '' is therefore not allowed access

I Configured The Microsoft.AspNet.WebApi.Cors - NuGet package, as follows:

public static void Register(HttpConfiguration config)
        var cors = new EnableCorsAttribute(
                //to-do allow cross domains for all sites
                origins: "*", //and also tried "," gives same result
                headers: "*",
                methods: "*") {SupportsCredentials = true};


I traced the Origin header values on the server. I put the following code in the service 'global.asax' :

protected void Application_BeginRequest()
            var origin = HttpContext.Current.Request.Headers["Origin"];

            if (origin != null )
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");

The problem happens when user clicks back button form '' to '', the origin sent with the request is '', and there that is what the service allows access to: HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", '');

Any Way around this?

Note that I can't put '*' because the requests are authenticated.

nr: #1 dodano: 2017-01-01 12:01

have you tried to put in your StratUp.cs file something like:

var corsPolicy = new CorsPolicy
                AllowAnyMethod = true,
                AllowAnyHeader = true,
                SupportsCredentials = true,
                Origins = { "", "", "http://localhost:39372" }


            app.UseCors(new CorsOptions
                PolicyProvider = new CorsPolicyProvider
                    PolicyResolver = context => Task.FromResult(corsPolicy)

And in your web.config in your webserver section maybe like this:

      <remove name="FormsAuthentication" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Source Show
◀ Wstecz