问题描述
我有两个在本地运行的应用程序。一种是提供JSON响应的ASP.NET Core Web API()。另一个是调用该API的Javascript应用程序()。我正在测试的API端点是一个POST请求,并且我已与Fiddler确认此端点正在工作。
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.
当我从Javascript应用发出POST请求时在Chrome中,我看到此错误:
When I make the POST request from my Javascript app in Chrome I see this error:
但是,这是我的API 启动
的全部内容:
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.
这是我从Fiddler的端点收到的原始响应:
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"}]
如您所见,没有 Access-Control-Allow-Origin
标头存在。
As you can see, no Access-Control-Allow-Origin
header is present.
推荐答案
您可以尝试在services.UseCors()调用中而不是services.AddCors()上直接配置CORS选项。
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();
...
}
这篇关于无法使CORS适用于ASP.NET Core Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!