Cors error in Angular 6 .Net core 2.2 App

China☆狼群 提交于 2020-02-02 13:39:43

问题


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

回答1:


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.




回答2:


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

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




回答3:


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.



来源:https://stackoverflow.com/questions/55154796/cors-error-in-angular-6-net-core-2-2-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!