I am having a CORS issue on an IIS web server. I am able to run the below code on my local dev machine running IIS Express (changing appropriate ports and URLs) but I am getting a cors error when I try an access the app once its deployed. The error (I know all over the internet) is
Access to fetch at 'https://example.com:5001/api/Person/PostPerson' from origin 'https://example.com:44337' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am working on a .NET core 5.0 C# Web API app project. Below is my Person model that I am trying to POST.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Below is my person controller
[Route("api/[controller]/[action]")]
[ApiController]
public class PersonController : ControllerBase
{
private JsonSerializerSettings _jsonSettings;
[EnableCors("mypolicy")]
[HttpPost]
public string PostPerson([FromBody]Person person)
{
return JsonConvert.SerializeObject("success", _jsonSettings);
}
}
Below is the startup.cs methods.
ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder => builder.WithOrigins("https://localhost:44363").AllowAnyHeader());
options.AddPolicy("mypolicy", builder =>
builder.WithOrigins("https://example.com:44337").AllowAnyHeader());
});
Configure method
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("mypolicy");
});
}
I also checked connectivity to the api from my laptop using Postman
I appreciate your time, Thanks!
remove all your cors code and place this at the top of ConfigureServices
services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
replace yours with this
app.UseRouting();
app.UseCors("AllowAnyOrigins");
app.UseAuthorization();
only if this code is working you can try to replace builder.AllowAnyOrigin() with this
builder.WithOrigins("http://localhost:44363",
"https://example.com")