Response to preflight request doesn't pass access control check (Angular2) Response to preflight request doesn't pass access control check (Angular2) asp.net asp.net

Response to preflight request doesn't pass access control check (Angular2)


I got it resolved by adding following lines to web.config.

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

Thanks.


Adding Access-Control-Allow-Origin header for the preflight request during Application_BeginRequest in Global.asax.cs worked for me.

Global.asax/Global.asax.cs

protected void Application_BeginRequest(Object sender, EventArgs e)    {        // Preflight request comes with HttpMethod OPTIONS        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")                    {            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");                           // The following line solves the error message            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");            // If any http headers are shown in preflight error in browser console add them below            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");            HttpContext.Current.Response.End();        }    }

After solving this issue, the application threw errors on browser console that certain headers are not mentioned in preflight response.

Once the headers were added to Access-Control-Allow-Headers header of the preflight response it got resolved.


protected void Application_BeginRequest(Object sender, EventArgs e){    // Preflight request comes with HttpMethod OPTIONS        // The following line solves the error message        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")                {        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");                       // If any http headers are shown in preflight error in browser console add them below        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");        HttpContext.Current.Response.End();    }}

This above code worked fine