Startup.cs
中启用CORS如下所示:
将
services.AddCors();
添加到ConfigureServices
中。将中间件添加到
Configure
中:我知道这里的顺序很重要(ASP.NET 5: Access-Control-Allow-Origin in response),因此我将此调用放在方法的顶部,仅在日志记录或诊断中间件之前; 这是我的完整方法:
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();
}
localhost
CORS用于开发,并涉及到一个Angular2 CLI应用程序。本地CORS正常工作,我的客户端和API应用程序在同一localhost上的不同端口上,因此这是“真正”的跨源(我之所以强调这一点,是因为我在这里找到的建议:https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas:该文章的作者注意到响应中的CORS头仅在实际需要时发送,即在真正的跨源环境中)。
使用Fiddler我可以成功访问远程API,但我没有得到Access-Control-Allow-Origin
头部信息。因此,当通过浏览器(通过我的客户端应用程序)调用API时,即使服务器返回200,AJAX请求也会失败。示例Fiddler请求(成功):
GET http://mywebapisiteurl/api/values HTTP/1.1
User-Agent: Fiddler
响应:
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"]
尝试访问部署在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.
以下是使用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 {}
总之,看起来ASPNET API服务器没有返回期望的CORS头,因此我的基于浏览器的客户端无法在不同的来源上托管。然而,CORS设置似乎是正确的,至少从上面引用的文档来看;我处于真正的跨源环境中;并且我将中间件放在其他中间件之前。也许我漏掉了一些显而易见的东西,但是在搜索时这些都是我找到的所有建议。有什么提示吗?
更新:
回复 @Daniel J.G:从Fiddler中的请求/响应来看是成功的:
GET http://theapiserver/api/values HTTP/1.1
User-Agent: Fiddler
Host: theapiserver
Origin: http://theappserver/apps/prin
并且:
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"]
Angular2(Plunker)的请求/响应失败,如报告所述。通过检查网络流量,我只能看到预检请求:
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
在此之后,请求失败并且没有更多的流量发送到服务器。报告的问题是由于响应中缺少头部信息导致的 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.