ASP.NET Core CORS WebAPI: no Access-Control-Allow-Origin header

asp.net core no 'access-control-allow-origin' header is present on the requested resource.
asp.net core enable cors
asp.net core cors not working
enable cors in web api c#
asp.net mvc enable cors
asp.net core 3.0 cors
asp.net core 2.2 cors not working
enable cors in web api stackoverflow

I have deployed my ASP.NET Core web API to Azure, and I can access its endpoints using Swagger or a web debugger like Fiddler. In both cases (same origin in Swagger, different origin using Fiddler from my computer), when accessing the APIs I get the expected result, with CORS enabled as follows in my Startup.cs:

  1. add services.AddCors(); to ConfigureServices.

  2. add the middleware to Configure: I'm aware that order here matters (ASP.NET 5: Access-Control-Allow-Origin in response), so I am placing this call at the top of the method, only preceded by logging or diagnostic middleware; here is my full method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory,
    IDatabaseInitializer databaseInitializer)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    loggerFactory.AddNLog();

    // to serve up index.html
    app.UseDefaultFiles();
    app.UseStaticFiles();

    // http://www.talkingdotnet.com/aspnet-core-diagnostics-middleware-error-handling/
    app.UseDeveloperExceptionPage();
    app.UseDatabaseErrorPage();

    // CORS
    // https://docs.asp.net/en/latest/security/cors.html
    app.UseCors(builder =>
            builder.WithOrigins("http://localhost:4200", "http://www.myclientserver.com")
                .AllowAnyHeader()
                .AllowAnyMethod());

    app.UseOAuthValidation();
    app.UseOpenIddict();
    app.UseMvc();

    databaseInitializer.Seed().GetAwaiter().GetResult();
    env.ConfigureNLog("nlog.config");

    // swagger
    app.UseSwagger();
    app.UseSwaggerUi();
}

The localhost CORS is used during development, and refers to an Angular2 CLI app. CORS is working fine locally, and my client and API apps are on different ports on the same localhost, so this is "true" cross origin (I'm remarking this because of the suggestions I found here: https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas: the author of the post notices that the CORS header in the response is sent only when actually required, i.e. in true cross-origin environments).

Using Fiddler I can succesfully access the remote API, but I get NO Access-Control-Allow-Origin header. Thus, when calling the API from the browser (through my client app) the AJAX request fails, even if the server returns 200. Sample Fiddler request (success):

GET http://mywebapisiteurl/api/values HTTP/1.1
User-Agent: Fiddler

response:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=3d551180c72208c1d997584c2b6119cf44e3a55c868f05ffc9258d25a58e95b1;Path=/;Domain=prinapi.azurewebsites.net
Date: Thu, 01 Dec 2016 10:30:19 GMT

["value1","value2"]

When trying to access the remote API deployed on Azure, my client app always fails its AJAX request with error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.myclientserver.com' is therefore not allowed access.

Here is a sample client code using Angular2 (using Plunker):

import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { Http, Headers, Response } from '@angular/http';
import { HttpModule } from '@angular/http';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button (click)="test()">test</button>
    </div>
  `,
})
export class App {
  name:string;
  constructor(private _http: Http) {
    this.name = 'Angular2'
  }
  public test() {
    this._http.get('http://theapisiteurlhere/api/values',
    {
        headers: new Headers({
          'Content-Type': 'application/json'
        })
    })
    .subscribe(
      (data: any) => {
        console.log(data);
      },
      error => {
        console.log(error);
      });
  }
}

@NgModule({
  imports: [ BrowserModule, HttpModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

To sum up, it seems that the ASPNET API server is not returning the expected CORS headers, and thus my browser-based client hosted on a different origin fails. Yet, the CORS setup seems to be OK, at least judging from the documentation quoted above; I'm in true cross-origin environment; and I'm placing the middleware before the others. Maybe I'm missing something obvious, but googling around these are all the recommendations I found. Any hint?

UPDATE

In reply to @Daniel J.G: the request/response from fiddler are successful:

GET http://theapiserver/api/values HTTP/1.1
User-Agent: Fiddler
Host: theapiserver
Origin: http://theappserver/apps/prin

and:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: http://theappserver/apps/prin
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=3d551180c72208c1d997584c2b6119cf44e3a55c868f05ffc9258d25a58e95b1;Path=/;Domain=theapiserver
Date: Thu, 01 Dec 2016 14:15:21 GMT
Content-Length: 19

["value1","value2"]

The request/response from Angular2 (Plunker) instead fail, as reported. By inspecting the network traffic, I can see the preflight request only:

OPTIONS http://theapiserver/api/values HTTP/1.1
Host: theapiserver
Proxy-Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://run.plnkr.co
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://run.plnkr.co/h17wYofXGFuTy2Oh/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6

HTTP/1.1 204 No Content
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=3d551180c72208c1d997584c2b6119cf44e3a55c868f05ffc9258d25a58e95b1;Path=/;Domain=theapiserver
Date: Thu, 01 Dec 2016 14:23:02 GMT

After this, the request fails and no more traffic goes to the server. The reported issue is that Response to preflight request doesn't pass access control check, again because of lack of the header in the response:

XMLHttpRequest cannot load http://theapiserver/api/values. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://run.plnkr.co' is therefore not allowed access.

Here is the answer to my own question, copied from the comments: I had not noticed that in Azure portal there is a CORS section. If I don't enter any allowed origin there, my code-based configuration seems to be totally irrelevant. This looks odd to me, as I'm forced to duplicate URLs here, but once I added * to the allowed origins there it worked.

Enabling Cross-Origin Requests in ASP.NET Web API 2, Here is the answer to my own question, copied from the comments: I had not noticed that in Azure portal there is a CORS section. If I don't enter  "XMLHttpRequest cannot load x Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'x' is therefore not allowed access. The response had HTTP status code 502."

Adding the .AllowAnyHeader() method could fix your problem

app.UseCors(builder => builder.WithOrigins("http://localhost:4200")
                              .AllowAnyMethod()
                              .AllowAnyHeader());

ASP.NET Core CORS WebAPI: no Access-Control-Allow-Origin , NET Core, what is the Same Origin Policy and how CORS works. NET Core 3 Web API. If the server allows Cross-origin requests from the Origin ( https://​example.com ), it sets the Access-Control-Allow-Origin header with its value The browser shall receive the response data, but this data shall not be  I'm running ASP.NET Core 2.0 (.NET Standard) on an Azure Web App. I am not using CORS middleware (i.e. no call to app.UseCors()), but I am setting up an access policy like so: The web app runs on www.mydomain.com and CORS is set up like.

The error message is very mis-leading. I was getting the same error after trying to add a new table to the DbContext. Angular was giving the no "Access-Control-Allow-Origin" error, but Postman was giving a 500 Internal Server error. The Login method was failing when trying to call _userManager.FindByEmailAsync(). Hope this helps someone else.

How to Enable CORS in ASP.NET Core By Example, CORS on ASP.NET. If you don't have access to configure IIS, you can still add the header through ASP. To enable cross-origin requests, add the [EnableCors] attribute to your Web API controller or controller method: described above can also be used to enable CORS across the API without annotating each controller: Access-Control-Allow-Origin Header and the ASP.NET Web API Here's a look at a solution to an Access-Control-Allow-Origin Header error, with background info, how to use the code, and more. by

WebApi Project ---> Right click on References ---> Search Core in Manage Nuget Packages section. Add Microsoft.AspNet.WebApi.Cors to the project by installing

Add the following code to the WebApi.Config file under the App_Start folder in the project.

var cors = new EnableCorsAttribute("","","*"); config.EnableCors(cors);

enter image description here

enter image description here

CORS on ASP.NET, NET Core application you'll need to use CORS to get XHR to talk across the Server: Kestrel Vary: Origin Access-Control-Allow-Credentials: true I went ahead and tested API calls through a browser and found: No CORS headers. CORS headers are only sent on cross domain requests and the ASP. This article shows how to enable CORS in an ASP.NET Core app. Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading

ASP.NET Core and CORS Gotchas, I want to enable CORS with Asp.Net Core 3.0 API project. This is except I added CORS settings from the documentation: Enable Cross-Origin Requests (C.​.. You only get CORS headers for requests to a different domain. Start Visual Studio and create a new ASP.NET Web Application (.NET Framework) project. In the New ASP.NET Web Application dialog box, select the Empty project template. Under Add folders and core references for, select the Web API checkbox. Add a Web API controller named TestController with the following code:

CORS not working in Asp.Net Core 3.0 · Issue #16672 · dotnet , Using CORS, a server can explicitly allow some cross-origin requests while If the URL terminates with / , the comparison will return false and no header will be​  No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API 3 CORS asp.net core webapi - missing Access-Control-Allow-Origin header

Enabling CORS in MVC, Here's a look at a solution to an Access-Control-Allow-Origin Header error, Origin 'http://localhost:58018' is therefore not allowed access. AspNet.WebApi.​Cors; By adding header information in Web.config NET Core API. Asp.net core web api that returns File is throwing No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access #123

Comments
  • Have you tried in fiddler setting the host and origin headers (host to the api host and origin to a different one to simulate cross origin)? It might also help if you post the details of a rquest made from angular.
  • Thank you, I updated my post (see at the bottom). In short, using Fiddler it's OK; using Angular2, the preflight request fails because there is no ACAO header in the server response, despite CORS being enabled.
  • You sure the origin http://run.plnkr.co is one of the allowed origins?
  • Guys, found the solution: I had not noticed that in Azure portal there is a CORS section. If I don't enter any allowed origin there, my code-based configuration seems to be totally irrelevant. This looks odd to me, as I'm forced to duplicate URLs here, but once I added * to the allowed origins there it worked.
  • I guess Azure sits in front of your app and does its own CORS check
  • For interested readers, this is a newer minimal sample for the password flow using OpenIdDict rc 3, which got some API changes: github.com/Myrmex/oid-credentials. Pay attention to the [Authorize] attribute parameter (end note in readme).
  • I've not tested but if this is true, what's the point of having CORS config in the code? thanks Naftis for pointing it out :)
  • You just saved me hours of troubleshooting! Thank you! I appreciate that MS is allowing CORS configuration in the Azure Portal, but it's frustrating that it's not more obvious. This seems to completely override the code-based CORS config (as others have said)...
  • this is un neccessary., you can use app.UseCors
  • I added * to allowed origins, but now my POST requests generate 500 errors, both in my Angular app and Postman tests
  • The OP is asking about ASP.NET CORE, not ASP.NET