简体   繁体   English

ASP.NET Core CORS WebAPI:没有 Access-Control-Allow-Origin 标头

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

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.我已将我的 ASP.NET Core Web API 部署到 Azure,并且我可以使用 Swagger 或像 Fiddler 这样的 Web 调试器访问它的端点。 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 :在这两种情况下(Swagger 中的同一来源,我的计算机上使用 Fiddler 的不同来源),在访问 API 时,我得到了预期的结果,在我的Startup.cs启用了 CORS,如下所示:

  1. add services.AddCors();添加services.AddCors(); to ConfigureServices .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;将中间件添加到Configure :我知道这里的顺序很重要( 响应 ASP.NET 5: Access-Control-Allow-Origin ),所以我将此调用放在方法的顶部,仅在记录或诊断之前中间件; 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. localhost CORS 在开发期间使用,指的是 Angular2 CLI 应用程序。 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, ie in true cross-origin environments). CORS 在本地运行良好,我的客户端和 API 应用程序在同一个本地主机上的不同端口上,所以这是“真正的”跨源(我之所以这么说是因为我在这里找到的建议: https://weblog.west -wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas :帖子的作者注意到响应中的 CORS 标头在实际需要时才发送,即在真正的跨域环境中)。

Using Fiddler I can succesfully access the remote API, but I get NO Access-Control-Allow-Origin header.使用 Fiddler 我可以成功访问远程 API,但我没有Access-Control-Allow-Origin标头。 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):因此,当从浏览器(通过我的客户端应用程序)调用 API 时,即使服务器返回 200,AJAX 请求也会失败。示例 Fiddler 请求(成功):

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:尝试访问部署在 Azure 上的远程 API 时,我的客户端应用程序总是失败其 AJAX 请求并出现错误:

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):这是使用 Angular2(使用 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.总而言之,似乎 ASPNET API 服务器没有返回预期的 CORS 标头,因此我托管在不同来源的基于浏览器的客户端失败。 Yet, the CORS setup seems to be OK, at least judging from the documentation quoted above;然而,CORS 设置似乎没问题,至少从上面引用的文档来看; 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 JG: the request/response from fiddler are successful:回复@Daniel JG:来自fiddler的请求/响应成功:

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.正如所报告的那样,来自 Angular2 (Plunker) 的请求/响应反而失败了。 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:报告的问题是Response to preflight request doesn't pass access control check ,同样是因为响应中缺少标头:

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.这是我自己的问题的答案,从评论中复制:我没有注意到Azure 门户中有一个 CORS 部分。 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.这对我来说看起来很奇怪,因为我被迫在这里复制 URL,但是一旦我将*添加到允许的来源中,它就起作用了。

Adding the .AllowAnyHeader() method could fix your problem添加 .AllowAnyHeader() 方法可以解决您的问题

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

I was facing similar error, but my error solved by keeping the pipeline in order.我遇到了类似的错误,但我的错误通过保持管道井然有序来解决。 (startup.cs -> configureServices) like (startup.cs -> configureServices) 喜欢

  app.UseRouting();
  app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
  app.UseEndpoints(endpoints => .....

The error message is very mis-leading.错误信息非常具有误导性。 I was getting the same error after trying to add a new table to the DbContext.尝试将新表添加到 DbContext 后,我​​遇到了同样的错误。 Angular was giving the no "Access-Control-Allow-Origin" error, but Postman was giving a 500 Internal Server error. Angular 没有给出“Access-Control-Allow-Origin”错误,但 Postman 给出了 500 Internal Server 错误。 The Login method was failing when trying to call _userManager.FindByEmailAsync().尝试调用 _userManager.FindByEmailAsync() 时登录方法失败。 Hope this helps someone else.希望这对其他人有帮助。

WebApi Project ---> Right click on References ---> Search Core in Manage Nuget Packages section. WebApi 项目 ---> 右键单击​​ References ---> 在 Manage Nuget Packages 部分中的 Search Core。 Add Microsoft.AspNet.WebApi.Cors to the project by installing通过安装将 Microsoft.AspNet.WebApi.Cors 添加到项目中

Add the following code to the WebApi.Config file under the App_Start folder in the project.将以下代码添加到项目中 App_Start 文件夹下的 WebApi.Config 文件中。

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

enter image description here在此处输入图片说明

enter image description here在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORS asp.net 核心 webapi - 缺少 Access-Control-Allow-Origin 标头 - CORS asp.net core webapi - missing Access-Control-Allow-Origin header ASP.NET Core CORS WebAPI:不保留 Access-Control-Allow-Origin 标头 - ASP.NET Core CORS WebAPI: persist no Access-Control-Allow-Origin header ASP.Net核心WebAPI - 请求的资源上没有“Access-Control-Allow-Origin”标头 - ASP.Net Core WebAPI - No 'Access-Control-Allow-Origin' header is present on the requested resource ASP.NET Core Web Api发送Access-Control-Allow-Origin:null CORS头和chrome是错误的,如何修复? - ASP.NET Core Web Api sending Access-Control-Allow-Origin: null CORS header and chrome is erroring, how to fix? ASP .NET 核心中 CORS 中的问题 - 响应中的“访问控制允许来源”header 的值不能是通配符 '* - Issue in CORS in ASP .NET Core - The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '* ASP.NET Core 6 中的“访问控制允许来源” - 'Access-Control-Allow-Origin' in ASP.NET Core 6 在Asp.net Core 2.1的Angular 6中不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present Angular 6 with Asp.net Core 2.1 Angular.js-CORS-ASP.NET-Rest API-在Access-Control-Allow-Origin标头中找不到原始 - Angular.js - CORS - ASP.NET - Rest API - Origin not found in Access-Control-Allow-Origin header 不存在“Access-Control-Allow-Origin”标头 - 面向 .net 框架 4.5.1 的 asp.net 核心 Web api - No 'Access-Control-Allow-Origin' header is present - asp.net core web api targeting .net framework 4.5.1 在Access-Control-Allow-Origin标头中找不到源[域]。 ASP .NET CORE API MVC - Origin [domain] not found in Access-Control-Allow-Origin header. ASP .net CORE API mvc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM