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

12,280

Solution 1

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();
}}

Solution 2

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

Solution 3

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

Share:
12,280

Related videos on Youtube

arame3333
Author by

arame3333

Updated on June 04, 2022

Comments

  • arame3333
    arame3333 almost 2 years

    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();
    }
    
    • Óscar Andreu
      Óscar Andreu over 6 years
      Did you add the content-type?
    • arame3333
      arame3333 over 6 years
      I put "Content-Type" in the header variable which is then included in the WithHeaders method as you can see in the code. I have since tried "AnyHeader()" with the same result.
    • Óscar Andreu
      Óscar Andreu over 6 years
      Sorry, I didn't explain so fin, I was speaking about the request. Do you have a raw HTTP request?
    • arame3333
      arame3333 over 6 years
      From Fiddler: OPTIONS localhost:17972/api/fault/10/close HTTP/1.1 Accept: / Origin: 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
  • arame3333
    arame3333 over 6 years
    I tried that but to no avail. I have been looking at the link - which is a good one - for some time trying to work out what I can do.
  • Óscar Andreu
    Óscar Andreu over 6 years
    You can also avoid libraries and add a cors rule in the web.config here: enable-cors.org/server.html
  • arame3333
    arame3333 over 6 years
    To try and get it working I am now using AllowAnyOrigin() but this does not solve the problem
  • Óscar Andreu
    Óscar Andreu over 6 years
    Still the same problem? can you update your question with the new code?