I need to add CORS support to a .NET core 3.1 API (was 2.2, but I decided to update at the same time). I thought this was going to be easy. The documentation here: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1 looks quite simple. I want to support the same CORS policy across all endpoints. So, I thought I could leave my controllers alone and just make the changes to startup.cs. What am I missing?
I have a POST endpoint, but the OPTIONS requests returns a 405 error. I thought the CORS middleware was supposed to handle the request, so that I don't have to think about CORS at all inside the controllers.
Startup.cs
namespace MyAPI
{
public class Startup
{
readonly String ALLOW_ALL = "AllowAll";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// services.Configure<IISOptions>(options =>
// {
// options.AutomaticAuthentication = true;
// });
services.AddLogging();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
// .AllowCredentials();
});
});
services.AddMvc(MvcOptions => MvcOptions.EnableEndpointRouting = false);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
// if (env.IsDevelopment())
// {
// app.UseDeveloperExceptionPage();
app.UseCors();
// }
app.UseEndpoints(endpoints => endpoints.MapControllers());
app.UseMvc();
}
}
}
MyController.cs
namespace MyProj.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FacilitiesController : ControllerBase
{
public FacilitiesController()
{
}
[HttpPost]
public JsonResult FloorPlanURL([FromBody] UniqueFloor theFloor)
{
<stuff happens>
return new JsonResult(new {success = true, url = out});
}
I've been through several iterations, looking here as well: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-endpoint-routing. I'm probably missing something small and simple. I could add manual OPTIONS handlers in all the controllers, but that seems like a pretty lousy solution.
Access-Control-Request-Method
andOrigin
headers or middleware will reject with 405. – Residence