简体   繁体   中英

CORS: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

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:

[HttpPost("uploadimage")]
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 =>
                      {
                          builder.WithOrigins("http://example.com",
                                              "http://www.contoso.com");
                      });
});

and

app.UseCors(MyAllowSpecificOrigins);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM