简体   繁体   中英

In ASP.NET, Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header

I am using a Web Core API and have set up CORS as follows;

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        ...
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
var url = Configuration["origenUrl"];
            var header = "Content-Type";
            app.UseCors(
                options => options.WithOrigins(url).WithHeaders(header).AllowAnyMethod().AllowCredentials()
            );
        }

This setup works fine for Get Requests. But for my Put request;

   $.ajax({
        url: url,
        method: "PUT",
        xhrFields: { withCredentials: true }
    })
        .done(callback)
        //.fail(errorMessage);
        .fail(function (jqXHR, textStatus, errorThrown) {
            alert("Something went wrong: " + textStatus + " " + errorThrown);
            errorCallback();
        });

I get this error message;

XMLHttpRequest cannot load http://localhost:17972/api/fault/1/close .

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:12528 ' is therefore not allowed access. The response had HTTP status code 401.

From Fiddler my http request is;

OPTIONS http://localhost:17972/api/fault/10/close HTTP/1.1

Accept: /

Origin: http://localhost:12528

Access-Control-Request-Method: PUT

Access-Control-Request-Headers: accept

UA-CPU: AMD64

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64;Trident/7.0; rv:11.0) like Gecko

Host: localhost:17972

Content-Length: 0

DNT: 1

Connection: Keep-Alive

Pragma: no-cache

So how do I fix this?

EDIT I have also tried this code just to get it working, but I get the same error;

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //var url = Configuration["originUrl"];
            //app.UseCors(
            //    options => options.WithOrigins(url).AllowAnyHeader().AllowAnyMethod().AllowCredentials()
            //);
            app.UseCors(
                options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials()
            );
            app.UseMvc();
}

Try with AllowAnyHeader instead of WithHeaders, it must works. The problem is that you are requiring a "Content-Type" header, but isn't being sent. If you wants to keep the WithHeaders check, add "Access-Control-Request-Method".

More info: https://docs.microsoft.com/en-us/aspnet/core/security/cors

I know this is a bit old, but I just ran into the same problem and was able to work out the issue. I was following a Microsoft guide on how to enable CORS globally. I set the following code within the Startup.cs file...

services.AddCors(options =>
{
    options.AddPolicy(MyAllowSpecificOrigins,
        builder =>
        {
            builder.WithOrigins("http://localhost");
        });
});

The guide did have an example of using a localhost, however it was at the very end within the "Test CORS" section. There, they show that you have to have the port number as well. I changed my code to:

services.AddCors(options =>
{
    options.AddPolicy(MyAllowSpecificOrigins,
        builder =>
        {
            builder.WithOrigins("http://localhost:3000")
                .AllowAnyHeader();
        });
});

I also added the AllowAnyHeader (as mentioned above) and everything works great! HTH

I was having a similar problem where GET requests would work fine, but POST requests would give me the same angry message as OP got. The code below worked for me, the other answers weren't quite complete in my case:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(
            builder =>
            {
                builder.WithOrigins("http://localhost:1337")
                       .AllowAnyHeader()
                       .AllowAnyMethod();
            });
    });

    services.AddControllers();
    services.AddRazorPages();
}}

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