简体   繁体   中英

Cors error in Angular 6 .Net core 2.2 App

I have developed the .Net Core MVC (angular) app and .net core Api app

In both apps I have enabled the CORS in both Web app and api

.Net Core

 services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });
// in Configure

    app.UseCors("CorsPolicy");

Angular

For all Get and Post add the headers like below

get(url: string, options?: any) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Accept', 'applcation/ json');
    options = { headers: headers };
    const _url = this.webapiurl + url;
    return this.http.get(_url, options);    
  }

Still facing the CORS error

Access to XMLHttpRequest at 'http://etestservice.qa.com:5003/QA/api/test/GetDetails?email=abc@gmail.com' from origin 'http://etestweb.qa.com::5002' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

In startup.cs file

public void ConfigureServices(IServiceCollection services)
{
        services.AddMvc();

        // app settings configuration.
        services.AddCors(options =>
        {
            // this defines a CORS policy called "default"
            options.AddPolicy("AllowSpecificOrigin", policy =>
            {
                var corsUrlSection = Configuration.GetSection("AllowedOrigins");
                var corsUrls = corsUrlSection.Get<string[]>();
                policy.WithOrigins(corsUrls)
                    .AllowAnyHeader()
                    .WithExposedHeaders("X-Pagination") // add any customer header if we are planning to send any 
                    .AllowAnyMethod();
            });
        });

}



public void Configure(IApplicationBuilder app, IHostingEnvironment environment, ILoggerFactory loggerFactory)
{

        app.UseExceptionMiddleware();

        // Use HTTPS Redirection Middleware to redirect HTTP requests to HTTPS.
        app.UseHttpsRedirection();

        app.UseCors("AllowSpecificOrigin");

        app.UseMvc();

}

In API,

[EnableCors("AllowSpecificOrigin")]
public class Controller
{
   // code...
}

The order of the Middleware components is a must. So check it. I have attached here my project code.

Add [EnableCors("CorsPolicy")] attribute above your controller

Also refer this How to enable CORS in ASP.NET Core

My startup.cs file:

    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));

//In configure
        app.UseHttpsRedirection();
        app.UseMvc();
        app.UseCors("MyPolicy");

And you need to enable cors in your controller class as follows.

[Route("api/[controller]")]
    [ApiController]
    [EnableCors("MyPolicy")]
    public class controllerName : ControllerBase
    {
// class boby

}

It works perfectly for me.

Probably the web api is not handling the preflight request (HTTP VERB - OPTIONS) correctly. The

Microsoft.AspNetCore.Cors

will allow you to do CORS with built-in features, but it does not handle OPTIONS request. The best workaround so far is creating a new Middleware as suggested in a previous post. Check the answer marked as correct in the following post:

Enable OPTIONS header for CORS on .NET Core Web API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM