I'm trying to enable CORS for a specific API controller in an ASP.NET Core application. First, I install the NuGet package, and this is added to my .csproj
:
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
Then, I add the following in my ConfigureServices
:
services.AddCors(options => {
options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
After that, if I add this in my Configure
, it works:
app.UseCors("AllowAll");
However, this enables CORS for all controllers. I just want to enable it for SessionApiController
. If I instead add the EnableCorsAttribute
to the controller:
[Route("api/session")]
[EnableCors("AllowAll")]
[ApiController]
public class SessionApiController : Controller {
[...]
[Route("init")]
public JsonResult InitSession() {
[...]
}
}
... it doesn't work, and Chrome gives me a CORS error when I try to access the /api/session/init
endpoint ("No 'Access-Control-Allow-Origin' header is present on the requested resource."). What am I missing here?