我的项目在 Visual Studio 上完美运行,但在我发布 ASP.NET Core Web API 并构建 Angular 代码后,由于此错误,我无法访问 API 函数:
从源“http://localhost:44413”访问“http://localhost:7173/login/login”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否“ Access-Control-Allow-Origin' 标头存在于请求的资源上。
我检查了“网络”选项卡,发现请求中没有添加 http 标头。
我真的不知道为什么发布后会出现这种情况。
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
......
app.UseCors(MyAllowSpecificOrigins);
这是角度调用:
let httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*'
})
};
this.http.post<string>('http://localhost:7173/login/login', this.user, httpOptions)
.subscribe(results => { console.log(results); },
error => console.log(error));
这是我的代理 json:
{
"/*": {
"target": "http://localhost:7173/",
"secure": false,
"logLevel": "debug"
}
}
我做了一切并改变了一切,但错误仍然是一样的。
在 Visual Studio 上一切正常,但发布后我不知道原因是什么。
builder.Services.AddCors(options => options.AddPolicy(name: "AppOrigins",
policy => { policy.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader(); }));
app.UseCors("AppOrigins");
https://github.com/mammadkoma/WebApi/blob/master/WebApi/Program.cs
服务和中间件的顺序很重要。