CORS: Response To Preflight Request Doesn't Pass Access Control Check: It Does Not Have HTTP Ok Status

- 1 answer

What I am trying to do used to work just fine before, I don't know what has happened, maybe they updated CORS policy in the browser side

I am trying to upload a file to my ASP.NET 6 API, my endpoint is as follows:

public ActionResult<string> UploadImage(
    [FromForm] IFormFile image,
    [FromForm] int? days = 30,
    [FromForm] MediaType? type = MediaType.AccountImage)
    //do things
    return url;

If I try to call this in POSTMan it will work fine and return the URL. But when I try to call it from my browser I get this:

Access to fetch at 'http://localhost:15040/api/media/uploadimage' from origin 'http://localhost:5126' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Here is my CORS middleware configuration:

ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
ctx.Response.Headers.Add("Access-Control-Allow-Methods", "*");
ctx.Response.Headers.Add("Access-Control-Allow-Headers", "append,delete,entries,foreach,get,has,keys,set,values,Authorization,Origin, Content-Type, X-Auth-Token,Accept, X-Requested-With, Access-Control-Request-Method, Access-Control-Request-Headers");

I checked in postman and the headers are present. I have set a breakpoint within the server and the request is not even being sent to the server, the breakpoint doesn't hit and the method is not called...

This is my code to upload the file from the client:

var form = await file.GenerateImageForm();
var uri = new Uri("HTTP://localhost:15040/api/media/uploadimage");
var req = new HttpRequestMessage
    Method = HttpMethod.Post,
    Content = form,
    RequestUri = URI,
req.Headers.Add("Allow-control-allow-origin", "*");
var ret = await HttpClient.SendAsync(req);

How can I upload my files to my server?



The way you implement it, differs from the docs.

With the amount of details you provided it's hard to tell what is wrong, but my best guess is you left out implementing an OPTIONS method on your endpoint causing it to fail the pre-flight.

Best is to just go for the options as described in the docs unless you have a very good reason not to:

builder.Services.AddCors(options =>
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>