Harshal Bulsara
Harshal Bulsara

Reputation: 8264

C# Web API Throws CORS error after framework upgrade from 4.5.2 to 4.7.2

I have an ASP.NET MVC and REST Web API written in C#. A few days back we have upgraded the framework version for both ASP.NET MVC and Web API from 4.5 to 4.7.2 and after that, it is continuously throwing CORS error saying my ASP.NET MVC URL is not able to call REST

No 'Access-Control-Allow-Origin' header present on the requested resource

The interesting part is that when we started this project a few years back we have already configured the fix which is mentioned in this Answers and is working fine up to this point.

I even tried other answers from that question but it still throwing the same error. I even upgraded all NuGet packages but facing the same issue.

I am calling API from my ASP.NET MVC app via Ajax.

Here is my Global.asax.cs file configuration

protected void Application_BeginRequest()
    {
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS,");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "userId,ApiKey");
            HttpContext.Current.Response.End();
        }
    }

I am missing any configuration?

Upvotes: 2

Views: 1910

Answers (1)

Shahid Syed
Shahid Syed

Reputation: 639

Here is the reason it stopped working for you after the framework upgrade.

On 4.5.2, Application_BeginRequest will be fired for OPTIONS.
On 4.7.2, Application_BeginRequest won't be fired for OPTIONS.

If you add following to your web.config then Application_BeginRequest will be fired for OPTIONS on 4.7.2.

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

Source code: https://github.com/ShahJe/MVCOptionsDemo

Upvotes: 4

Related Questions