I have CORS working fine in "normal" {controller}/{action}/{id?} controllers. However CORS does not work in action methods with specific [Route("routname")] attributes.
Sample controller with route:
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
[HttpPost]
public async Task<ActionResult<Guid>> Post([FromBody] Customer value)
{
...
}
[HttpPost]
[Route("payment")]
public async Task<ActionResult<CustomerPaymentResponse>> Pay([FromBody] CustomerPaymentRequest value)
{
...
}
My ConfigureServices method in startup.cs file looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(c =>
{
c.AddPolicy("AllowAnyOrigin", options => options
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddRouting();
services.AddControllers();
}
and Configure method looks like this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("AllowAnyOrigin");
});
}
If I POST to /api/customer CORS is working.
If I POST to /api/customer/payment CORS does not work (Chrome says: "... 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.")
I have followed the provided answer for Can't enable CORS for specific API controllers in ASP.NET Core WebApp targeting netcoreapp3.0 but issue still remains for me.
Any thoughts?