0

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

danijeljw-RPC
  • 345
  • 2
  • 13
  • Can you show how the AddCors method looks like in your startup.cs? – M. Radević May 27 '22 at 09:55
  • @M.Radević There is no `Startup.cs` in dotnet-core 6. The `AddCors` method is shown in my first code block, that starts with `builder.Services.AddCors(options =>` at the top of my question. I added a specific URL as that was how I was testing the public CORS for the HTTP PATCH request. – danijeljw-RPC May 27 '22 at 11:30
  • maybe the issue appeared in the test tool.... – Tiny Wang May 30 '22 at 02:55

1 Answers1

0

I created a .net 6 MVC app, and in my controller, I followed the document you mentioned and added a request like this:

[HttpPatch]
public IActionResult JsonPatchWithModelState([FromBody] JsonPatchDocument<Customer> patchDoc)
{
    if (patchDoc != null)
    {
        var customer = new Customer {
            customerName = "a"
        };

        patchDoc.ApplyTo(customer, ModelState);

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        return new ObjectResult(customer);
    }
    else
    {
        return BadRequest(ModelState);
    }
}

Then in the Program.cs, adding cors policy:

builder.Services.AddControllersWithViews().AddNewtonsoftJson();
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "MyAllowAllHeadersPolicy",
        policy =>
        {
            //policy.WithOrigins("https://cors-test.codehappy.dev")
            policy.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
});
...
..
.
app.UseRouting();
app.UseCors("MyAllowAllHeadersPolicy");

And now test in the tool you mentioned :

enter image description here

But when I create a SPA to test the api

$("#btn2").click(function() {
    alert(2);
    $.ajax({
        headers : {
            'Accept' : 'application/json',
            'Content-Type' : 'application/json'
        },
        url : 'https://localhost:7151/home/JsonPatchWithModelState',
        type : 'PATCH',
        data : JSON.stringify({customerName: "xxxx"}),
        success : function(data) {
            alert("OK");
        },
        error : function(data) {
            alert("error");
        }
    });
});

It can access the api.

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29