【发布时间】:2018-07-29 09:36:27
【问题描述】:
我的应用程序在 IE 浏览器中运行良好,但由于 CORS 问题,它在 Chrome 浏览器中无法运行。
问题是
无法加载http://localhost:52487/api/Authentication/:当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。因此,Origin 'http://localhost:4200' 不允许访问。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
我在前端使用 angular 2,在后端使用 Asp.net core 1.0。我试过了
这是我的启动代码
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll", p =>
{
p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Add framework services.
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<Data>(Configuration.GetSection("Data"));
services.Configure<COCSettings>(Configuration.GetSection("COCSettings"));
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
AppSettings.ConnectionString = Configuration["Data:DefaultConnectionString"];
// *If* you need access to generic IConfiguration this is **required**
services.AddSingleton<IConfiguration>(Configuration);
// Injecting repopsitories with interface
AddServices(services);
// Add Json options
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
// 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(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMiddleware(typeof(ErrorHandling));
app.UseMiddleware(typeof(GetNoCache));
app.UseCors("AllowAll");
app.UseMvc();
}
这就是我从 UI(angular) 端调用 API 的方式
constructor(private http: Http) {
this.headers = new Headers();
this.headers.append('Accept', 'application/json');
}
GetMaintainCOC(FYONId) {
return this.http.get(this.apiUrl + 'GetCertificationofConformity?FYONId=' + FYONId, { withCredentials: true })
.map(responce => <any>responce.json())
.catch(error => {
return Observable.throw(error);
});
}
【问题讨论】:
-
“尝试了一些......以前的答案” - 你到底尝试了什么?您是否尝试设置像this 这样的白名单,该解决方案的哪一部分不适合您?
-
不确定你在问什么(很明显你有什么问题 - 你不同意 CORS 政策 - stackoverflow.com/questions/19743396/…) - 请澄清你想要实现的目标......听起来不使用 Chrome 是唯一的选择(至少在其他浏览器与相同策略保持一致之前的一段时间内),因为您明确地
p.AllowAnyOrigin()... -
@Tewr 在
http.get()中添加了凭据 true。但我没有看到与这个确切问题相关的任何问题。所以我手动尝试了一些来自堆栈溢出和谷歌的建议。 -
AllowAnyOrigin如果您希望它与凭据一起使用,那么简单的方法是行不通的。所以不要设置 - 指定特定的来源。 -
@AlexeiLevenkov 这并不完全正确,因为
AllowAnyOrigin不需要转换为Access-Control-Allow-Origin: *。 ASP.NET 知道“*”不能与凭据一起使用,因此如果您指定AllowCredentials,则将使用请求来源。
标签: c# angular asp.net-web-api asp.net-core cors