Reputation: 2698
I am trying to connect to my .net core API from angular application. when I try to do that, I get an error saying:
Access to XMLHttpRequest at 'https://localhost:44378/api/recloadprime' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
below is the console messages from my angular application:
Here is what I did to resolve the error. I added services.addCors in ConfigureServices method in startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllers();
services.AddDbContext<db_recloadContext>();
}
In configure method, I put the following code:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAnyCorsPolicy");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
In my controller, I have the following code:
namespace RecLoad.Controllers
{
[Route("api/[controller]")]
[EnableCors("AllowAnyCorsPolicy")]
public class RecLoadPrimeController : ControllerBase
{
private readonly db_recloadContext _context;
public RecLoadPrimeController(db_recloadContext context)
{
_context = context;
}
I followed the instruction given in Microsoft documentation and one of the stackoverflow post:
https://stackoverflow.com/questions/42199757/enable-options-header-for-cors-on-net-core-web-api
and Microsoft article:
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
I spend lot of time going through other documentation and tried different code in startup.cs file, but this error is not going away.
Below is my api that runs fine:
[HttpGet]
public ActionResult<string> Get()
{
return "This is a test";
}
Below is the header from my developers tool:
I also enabled CORS extension in my chrome browser. Below is the image:
Any help will be highly appreciated.
Upvotes: 2
Views: 4349
Reputation: 9490
To make it work, you could try these things:
1) in ConfigureServices
method, call AddCors
to configure the CORS service, initially, to allow any origin:
services.AddCors(options =>
{
options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});
2) in Configure
method add UseCors
, this adds middleware to web application pipeline:
app.UseRouting();
app.UseCors("AllowAnyCorsPolicy");
app.UseMvc();
Since ASP.NET Core 3.1 .UseCors()
needs to be called after .UseRouting()
, as mentioned in https://github.com/dotnet/aspnetcore/issues/17830.
When this initial configuration is working, it can be later modified to your requirements.
Upvotes: 7