Forum Discussion
Ben_Pierce
Jan 02, 2024Copper Contributor
ASP.NET Core 8 Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.
I created a PATCH method in an ASP.NET Core Web API like this: #region Patch
/// <summary>
/// Patch TableName by id.
/// </summary>
// PATCH BY ID: /TableName/patch/{id}
[HttpPatch("[ac...
Jaiminsoni
Jan 10, 2024Copper Contributor
I have tried to solve and summarise your issue for the PATCH method not being allowed in Blazor due to CORS restrictions, let me know if this helps.
Understanding the Issue:
- CORS (Cross-Origin Resource Sharing): A browser security mechanism that restricts web pages from making requests to a different domain than the one that served the page.
- Preflight Requests (for non-standard methods like PATCH): Browsers send an initial OPTIONS request to check allowed methods before making the actual PATCH request.
- Access-Control-Allow-Methods Header: The server must explicitly list PATCH in this response header to grant permission.
Resolving the Issue in Blazor:
Configure CORS in Startup.cs:
- Add the CORS middleware:
services.AddCors(options =>
{
options.AddPolicy("AllowPATCH",
builder => builder.WithOrigins("http://localhost:5000") // Adjust origins as needed
.AllowAnyMethod() // Or explicitly list PATCH
.AllowAnyHeader();
});
- Apply the policy in the app's middleware pipeline:
app.UseCors("AllowPATCH");
Enable CORS in ASP.NET Core Web API (if applicable):
- Use EnableCors attribute on controllers or actions:
[EnableCors("AllowPATCH")]
[HttpPatch]
public IActionResult PatchData()
{
// ...
}
Ben_Pierce
Jan 16, 2024Copper Contributor
JaiminsoniThank you for the helpful suggestions. This turned out to be a conflict with Steeltoe. When using AddAllActuators the Steeltoe code is adding it's own CORS policy overriding anything that I was setting up. When adding each actuator separately then it works. This was a tough one to solve. I was only able to do that by looking at the CORS policy collection and noticing there was an additional one above mine.