【发布时间】:2020-01-01 09:37:39
【问题描述】:
我在同一台服务器上部署了两个项目。其中一个是 Angular 项目,另一个是 Angular 项目调用的.net CORE 中的 API。 在本地我没有这个问题,但是在服务器上,每次调用 API 时,我都会在浏览器控制台中收到此错误消息:
从来源>'http://myIPAdress:81/Configuration/CODE_CLIENT' 访问 XMLHttpRequest >'http://myIPAdress' 已被 CORS 策略阻止:请求的资源上不存在“Access-Control->Allow-Origin”标头
我推断问题来自 .NET Core 项目。我已经在 StackoverFlow 上尝试过建议的解决方案,但没有成功。 这是我在 .net Core 端的代码:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new
CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:80").AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug(LogLevel.Information);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
在 Angular 方面,我这样调用我的 API:
getConf(code : string){
var url = "http://MyIPAdress/Configuration";
return this.http.get<any>(url +'/'+ code)
}
在本地,我通过我的 API 访问数据,但不是在服务器上,有人知道为什么吗?
对不起我的英语和我的代码,我开始编程
编辑:我在服务器的 IIS 中添加了一个 HTTP 响应:Access-Control-Allow-Origin。现在我没有同样的错误,但是这个:
响应中“Access-Control-Allow-Credentials”标头的值是 >'',当请求的凭据模式为“包含”时,该值必须为“真”。 XMLHttpRequest 发起的请求的 >credentials 模式由 >withCredentials 属性控制。
【问题讨论】:
-
试试
builder => builder.WithOrigins("http://myIPAdress").AllowAnyHeader() -
@David 总是同样的问题...我不明白,我的角度调用好吗?
-
你确定服务器端直接调用net-core api吗?也许他们之间有代理?
-
尝试将呼叫
app.UseCors("AllowSpecificOrigin");移动到app.UseMvcWithDefaultRoute();之前,以便在呼叫app.UseAuthentication();之后
标签: .net angular cors asp.net-core-webapi