I am trying to enable CORS
just for GET
requests, but I seem to be struggling. From reading the documentation, I understand that this should be achievable by adding the WithMethods
method but doesn't seem working to me. Rather, I do not hit a CORS error, even when fetch
ing via POST
.
Below is my code
(Note that I am adding 2 UseCors
just to demonstrate that I have tried 2 overloads, both to no avail, both return fine with POST
).
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options=>{
options.AddPolicy("customPolicy",policy=>{
policy.WithOrigins("https://customsite.com").WithMethods("GET");
});
});
var app = builder.Build();
app.UseCors("customPolicy");
app.UseCors(options=>{
options.WithOrigins("https://customsite.com").WithMethods("GET");
});
app.MapPost("/", () => "Hello World!");
app.Run();
Is this a bug, or am I missing something?
CodePudding user response:
Turns out the docs https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder.withmethods?view=aspnetcore-6.0 are not so clear but I arrived at the answer from Andrew Locks book ASP NET CORE in Action 2e (page 597).
The WithMethods
method is permissive, not restrictive. By default, the simple headers (such as GET
, HEAD
and POST
as in our example) are allowed by default, (and I would not know how to disable one of them). But other method types, such as PUT
would fail in the example provided. Only by adding the correct name in the method, such as WithMethods("PUT")
will allow the request to participate in CORS
.