I have reviewed the information on Enable Cross-Origin Requests .NET 6 to no avail.
This only affects the HttpPatch
. When I run it in Swagger, no problems. When I try to test through 3rd party tool or CORS Test tool, I get errors.
The policy used dedicated for the CORS Test webapp already mentioned. Here is the code:
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "MyAllowAllHeadersPolicy",
policy =>
{
policy.WithOrigins("https://cors-test.codehappy.dev")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
When I run a test, I get this error message each time: It does not have the access-control-allow-origin
header set to *
. Without this header, requests from other domains cannot be made to it via a users browser.
All my other routes are OK, as I have enabled them on the Caddy Server globally using the following JSON snippet:
header {
# enable HSTS
Strict-Transport-Security max-age=31536000;
# disable clients from sniffing the media type
X-Content-Type-Options nosniff
# clickjacking protection
X-Frame-Options DENY
# keep referrer data off of HTTP connections
Referrer-Policy no-referrer-when-downgrade
# Content-Security-Policy: default-src 'self'
Access-Control-Allow-Origin *
Access-Control-Allow-Credentials true
Access-Control-Allow-Methods *
Access-Control-Allow-Headers *
}
On the particular route in the Controller that uses PATCH
(there is only 1 controller using PATCH for 1 item), I have this code too (abbreviated to show the annotations):
[EnableCors("MyAllowAllHeadersPolicy")]
[HttpPatch("{id:int}")]
public async Task<IActionResult> PatchAsync(int id, ...
The long error message in the Console from the browser is:
Access to XMLHttpRequest at 'https://web.site' from origin 'http://localhost:4200'
has been blocked by CORS policy: Response to preflight request doesn't pass access
control check: It does hot have HTTP ok status.
I don't want to post the entire URI, as this exposes my API and there are no Authorisations setup whilst it is undergoing development mode, so the URL's are just for example purposes.
Ideally I want to handle the preflight request
on the server side, in the WebApi project, so it returns a HTTP status code of 200 so that the browser will continue with sending the actual request.
I have read through quite a few documents and tried different policies, setting it to allow all, but to no avail.
Is there someone that might be able to point me in the right direction to resolve this?
My alternative, was to take a copy of the object, and re-publish it back to the API as a PUT command over the top of the object. This worked before but was a big overhead to handle the request. :-(
To enable the HTTP PATCH
I referenced this Microsoft article: aspnet Core 6 JsonPatch