【发布时间】:2018-02-20 17:37:39
【问题描述】:
我已经尝试了多个有关此主题的 StackOverflow 问题,但没有一个对我有用。我在控制台中不断收到此错误:
无法加载http://myserver:8080/api/user:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://myserver' 不允许访问。响应的 HTTP 状态代码为 401。
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://myserver","http://localhost").AllowAnyMethod().AllowAnyHeader().AllowCredentials()));
services.AddMvc(config => config.Filters.Add(typeof(CustomExceptionFilter))).AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton(Environment);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CorsPolicy");
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute()...// All of my routes
});
}
我也尝试在 AddPolicy 方法中使用 AllowAnyOrigin()。
当我在浏览器中查看我的 API 时,当我直接点击它时它工作正常:http://myserver:8080/api/user,但是,当我的 Angular 应用程序进行相同的调用时它不起作用:
ngOnInit() {
return this.http.get(`${environment.apiUrl}/api/user`).subscribe(
response => { ... }
);
environment.prod.ts:
export const environment = {
apiUrl: "http://myserver:8080",
production: true
};
有其他人在 Angular4 和 .Net Core 2.0 应用程序之间遇到过这些问题并知道解决方案吗?
【问题讨论】:
标签: angular iis windows-authentication asp.net-core-2.0