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

angular and web api in same project
angular 7 with asp.net mvc
angular 7 with web api
asp.net core web api and angular 7 crud
asp.net core web api and angular 8 crud
angular 4 with asp.net mvc 5 example
mvc angular 6
asp.net core angular 6

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.

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 }
        );
    }

Build a Basic Website with ASP.NET MVC and Angular, Create an API using a built-in template within Visual Studio. You'll You should have a new ASP.NET MVC application ready now, with all the  V. AngularJS with Server Side code (MVC Web API) The worry for any developer is that if Angular works with only HTML, then how can server side code be executed. Angular facilitates much more flexibility on this, any server side code can be plucked through Ajax call. So in this case, separate component can be designed to invoke by Angular.

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();
        }
    }

CRUD Operations In Angular 7 Using Web API, A Web API is used to provide data connectivity between the database and the front end application. On the UI side, I will use the Angular  Angular components are the basic building blocks of Angular Apps. A component decorator includes properties that allow you to define the template, file, CSS, and many more. Create ASP.NET MVC Project

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.

Asp.Net Core Web API and Angular 7 CRUD, Angular 7 CRUD with Asp.Net Core Web API CRUD Operations - Insert, and motivating Duration: 1:43:57 Posted: Jan 14, 2019 Serving MVC Views in an Angular + ASP.NET Core MVC Web API app - Stack Overflow I am building a web app based on Fabric.js. For most of the data management in the system, I intend to use Angular + WebAPI backend on an ASP.NET Core server. However, for the core part of the app

Angular and ASP NET Web API, From the middle pane select, ASP.NET Web Application next video we will discuss, how to Duration: 7:35 Posted: Aug 7, 2017 Create Angular app inside MVC 5 It would take few minutes to get all node modules downloaded. You can see in the folder structure that githouseapp folder is created in MVC 5 application folder structure. To ensure that the githouseapp is set up properly; navigate to folder path in command prompt and run the following command ng build.

Angular Front End Construction for ASP.NET Web API, Rather, Angular is meant for full-scale client-side application development of applications that consist of many pages and components that need to interact with  To achieve the above, follow the steps given below: Create a new ASP.NET MVC Empty Web Application. Add the following package in your application: AngularJS.Core AngularJS.Route Bootstrap EntityFramework AngularJS.Core AngularJS.Route Bootstrap EntityFramework Create a Model named Employee in Models

Building Web App using ASP.NET Web API Angular 7 and SQL Server, In this tutorial, we will create a REST API web service using ASP.NET Core Web API then create a front-end application with Angular 7. For the  I've written a number of AngularJS applications, including a couple that migrated from pre-existing WebForms and MVC applications, and the ASP.NET aspect evolves towards a platform for delivering the AngularJS app as the actual client, and for hosting the application layer the client communicates to via REST (using WebAPI).

Comments
  • Run Fiddler (telerik.com/download/fiddler) or your web debugger of choice and view the traffic. There's a preflight request happening and it's not returning a 200 OK. What is the status returned?
  • In The errors your address is https but you configured http.