Steven Morris
Steven Morris

Reputation: 51

MVC Web API Angular App ('http://localhost:4200' has been blocked by CORS policy)

I have been spending hours and hours about looking a way to enable my front end web app (Angular) to access my Asp.NET MVC (Controller) but it displays the following error:

Access to XMLHttpRequest at 'https://localhost:44344/Authentication/SignIn' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Angular URL: http://localhost:4200/login?returnUrl=%2F

MVC URL: https://localhost:44344/

Here also what I have added to my web.config

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
    <add name="Access-Control-Allow-Headers" value="*" />
    <add name="Access-Control-Allow-Methods" value="*" />
    <add name="Content-Type" value="application/json"/>

    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

I have also added the following line to the main controller:

 [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]

But the error es the same.

Here is the init of the controlles:

    [HttpPost]
    [AllowAnonymous]
    [DisableCors]
    public JsonResult SignUp(HF_Accnt_Access Company)

Can somebody help me out please.

Upvotes: 5

Views: 4313

Answers (3)

Prabhat
Prabhat

Reputation: 802

Add below code into Register method in WebApiConfig.cs file inside App_start folder.

var cors = new EnableCorsAttribute(origins: "", headers: "", methods: "*");

config.EnableCors(cors);

Note : If you add any where any configuration for cross origin please remove from there. Ex : Remove from web.config file. Add below code.

    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(origins: "*", headers: "*", methods: "*");
        config.EnableCors(cors);
        
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

Upvotes: 6

Ali Tabandeh
Ali Tabandeh

Reputation: 106

As Rick Strahl well explained it in his web blog, the problem is : Angular's default working environment runs a development server off a seperate port which is effectively a seperate domain and all calls back to the main ASP.NET site for the API calls effectively are cross domain calls. Alas those calls failed and upon closer inspection it was due to the fact that the CORS headers weren't getting sent. So the solution is:

// Add service and create Policy with options
public void ConfigureServices(IServiceCollection services)
{   
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials() );
    });        
    services.AddMvc(); 
}

and then you can either assign it globally to all controllers or to individual controllers as follow.

  1. assign globally

    public void Configure(IApplicationBuilder app){  
    
        // global policy - assign here or on each controller
    
        app.UseCors("CorsPolicy");
    
        // IMPORTANT: Make sure UseCors() is called BEFORE this
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    
  2. assign individually

    [EnableCors("CorsPolicy")]
    public class TestController : Controller
    

you might got this error :

The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the policy by listing individual origins if credentials needs to be supported

just simply remove allowCredentials() from a service.

hope it helps.

Upvotes: 1

Satish Patil
Satish Patil

Reputation: 458

The wildcard for Access-Control-Allow-Methods is not yet supported by all browsers.

Browser support is also tracked by MDN here

so change this line

[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]

TO

 [EnableCors(origins: "*", headers: "*", methods: "GET, POST, PUT, DELETE, OPTIONS")]

And you have to handle "OPTIONS" method separately in global.asax, as the browser will send a pre-flight request to the server

 protected void Application_BeginRequest()
    {
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

Upvotes: 0

Related Questions