Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS in .NET Core 2.0 "No 'Access-Control-Allow-Origin' header is present on the requested resource."

I have created a web api using Core 2.0 and when doing cross domain calls w/ cors enabled, receive the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

Below is my config in startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddLogging();
        services.AddMvc();
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAll",
                builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
        });

        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        app.UseMvc();
        app.UseCors("AllowAll");    
    }

According to every post/tutorial I see on stackoverflow or else where, this is the correct way to do it to allow all origins. What am I missing?

like image 803
Samuel Elrod Avatar asked Feb 06 '18 18:02

Samuel Elrod


People also ask

How do I enable CORS for origins net core?

There are three ways to enable CORS: In middleware using a named policy or default policy. Using endpoint routing. With the [EnableCors] attribute.

How do you fix no Access-Control allow Origin header is present on the requested resource?

Use a reverse proxy server or WSGI server(such as Nginx or Apache) to proxy requests to your resource and handle the OPTIONS method in the proxy. Add support for handling the OPTIONS method in the resource's code.


1 Answers

Try calling: app.UseCors("AllowAll"); before app.UseMvc();.

The documentation states the following:

To enable CORS for your entire application add the CORS middleware to your request pipeline using the UseCors extension method. Note that the CORS middleware must precede any defined endpoints in your app that you want to support cross-origin requests (ex. before any call to UseMvc).

like image 59
Mike Bovenlander Avatar answered Sep 25 '22 06:09

Mike Bovenlander