【发布时间】:2020-08-21 10:53:07
【问题描述】:
我受够了 .NET Core Web API 应用程序中的 CORS 错误。我已经完成了我认为的所有设置。
我做了什么
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(options =>
options.WithOrigins("http://localhost:4200/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyMethod());
//app.UseCors(builder => builder
// .AllowAnyOrigin()
// .AllowAnyMethod()
// .AllowAnyHeader()
// .AllowCredentials());
app.UseHttpsRedirection();
app.UseRouting();
}
即使现在它触发以下错误
从源“http://localhost:4200”访问“https://localhost:44331/api/kip”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我从 Angular 调用它
这是我的调用脚本
getProjects() {
let url:string=this.isServer?"http://localhost:51071/webservice1.asmx":"https://localhost:44331";
console.info(url);
return this.client.get(url+'/api/kip', {
withCredentials: true,
responseType: 'json'
});
}
我还在返回前在 API 的最后一行设置了一个断点,它到达那里没有任何问题。所以在调用 return 之后它会触发错误。我还单独尝试了返回 JSON 的 API。
这是我的控制器。
// GET: api/Kip
[HttpGet]
public KipProjects Get()
{
KipProjects proj = new KipProjects();
kip keyedin = new kip();
proj=keyedin.getKeyedinReport();
return proj;
}
【问题讨论】:
-
您是否尝试将
AllowCredentials添加到您指定来源的那个(options.WithOrigins("http://localhost:4200/"))? -
是的,那也试过了。但结果是一样的!
-
嗯,可能是 UseCors 需要在 UseRouting 之后:docs.microsoft.com/en-us/aspnet/core/security/…
标签: angular asp.net-core asp.net-web-api