I am trying to allow my ANgular app running at localhost:4200 to be able to request data from my back end api .NET Core 2.2 api running at localhost:44337. I have added a Cores policy in ConfigureServices, added it to Configure, and added a UseCors annotation on my endpoints, but I still get this error:
Access to XMLHttpRequest at 'https://localhost:44337/api/users/1' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Startup.cs
public string DefaultCorsPolicy = "DefaultCorsPolicy";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicy,
builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:4200/");
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(DefaultCorsPolicy);
app.UseMvc();
}
UsersController.cs
[HttpGet("{id}")]
[EnableCors("DefaultCorsPolicy")]
public async Task<ActionResult> GetUser(int id)
{
var settings = await _service.GetUser(id);
return Ok(settings);
}
If I add Response.Headers.Add("Access-Control-Allow-Origin", "*") in the actual GetUser method, it will work. But I don't want to brute force it.
I made sure to place both AddCors and UseCors calls at the beginning of ConfigureServices and Configure respectively. But it still will not work.
usersendpoint, I would expect to receive use data - instead, I get the error above in the console.