Tom Troughton
Tom Troughton

Reputation: 4325

Can't get CORS working for ASP.NET Core Web API

I have two applications running locally. One is an ASP.NET Core Web API (http://localhost:8081) serving up JSON responses. The other is a Javascript app (http://localhost:8080) making calls to the API. The API endpoint I'm testing with is a POST request and I've confirmed with Fiddler that this endpoint is working.

When I make the POST request from my Javascript app in Chrome I see this error:

Failed to load http://localhost:8081/api/search: 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:8080' is therefore not allowed access.

However, this is the full content of my API's Startup:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvcCore()
        .AddJsonFormatters()
        .AddCors(options =>
        {
            options.AddPolicy("DefaultCorsPolicy",
                builder => builder
                    .WithOrigins("http://localhost:8080")
                    .AllowAnyMethod());
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("DefaultCorsPolicy");

    app.UseMvc();
}

I've followed the Microsoft docs, so I'm not sure what I've missed.

Here is the raw response I get from this endpoint in Fiddler:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-Powered-By: ASP.NET
Date: Sat, 10 Mar 2018 09:23:46 GMT
Content-Length: 37

[{"id":1,"name":"lorem ipsum dolor"}]

As you can see, no Access-Control-Allow-Origin header is present.

Upvotes: 3

Views: 3378

Answers (1)

Nagesh Andani
Nagesh Andani

Reputation: 474

You can try to configure CORS options right in services.UseCors() call, rather than services.AddCors().

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


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(builder => builder
        .WithOrigins("http://localhost:8000")
        .AllowAnyHeader()
        .AllowAnyMethod()
    );

    app.UseMvcCore();
    ...
}

Note: Test it by Clearing the client side cache if any. On Chrome > F12 > Network Tab > Tick Disable Cache check box > Refresh the page.

Upvotes: 2

Related Questions