我想在我的webAPI中添加Access-Control-Allow-Origin
之类的额外标题,以便在另一个项目中使用此数据。目前我有这个错误:
无法加载http://localhost:49932/api/Restaurantes:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' http://localhost:4200'因此不允许访问。
49932端口运行我的API,4200端口是我的AngularJS客户端。我已按照this answer的建议尝试添加它们,但没有效果:
在appsettings.json中:
{
"ConnectionStrings": {
"ConexaoRestaurante": "data source=DESKTOP-R1CQGV1\\SQLEXPRESS;integrated security=SSPI;"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
},
"StaticFiles": {
"Headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH"
}
}
}
}
在Configure
方法中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// tried both the commented and uncommented part:
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
// Disable caching for all static files.
context.Context.Response.Headers["Access-Control-Allow-Origin"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Origin"];
context.Context.Response.Headers["Access-Control-Allow-Headers"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Headers"];
context.Context.Response.Headers["Access-Control-Allow-Methods"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Methods"];
}
});
/*
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
context.Context.Response.Headers["Access-Control-Allow-Origin"] = "*";
context.Context.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type";
context.Context.Response.Headers["Access-Control-Allow-Methods"] = "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH";
}
});
*/
app.UseMvc();
}
我还尝试创建Web.config,当您启动框架Core 项目并添加以下配置时,不会创建该文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
所以我想我在这部分之外做错了什么,有人知道这里有什么不对吗?
答案 0 :(得分:0)
Cors不仅仅是标题,请参阅this以获取更多信息。
要在.NET Core中设置CORS,您需要添加Cors服务并对其进行配置。
在ConfigureServices
添加以下电话:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
并使用Configure
方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Shows UseCors with CorsPolicyBuilder.
app.UseCors(builder =>
builder.WithOrigins("http://localhost:4200").AllowAnyHeader());
}