c# - 在启动中启用 CORS 失败并出现预检错误
问题描述
我正在尝试在 Startup.cs 中启用 CORS,但没有成功。我在端口 4200 上有一个 Angular 应用程序,试图与我的 c# Web 应用程序通信。我在 Angular 中不断收到此错误
无法加载http://localhost:52008/Account/GetJWT:预检响应没有 HTTP ok 状态。
我的研究似乎表明 CORS 未正确启用。知道我错过了什么吗?
public void ConfigureServices(IServiceCollection services)
{
.....
services.AddCors(options =>
{
options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.Build();
});
});
.........
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
.......
app.UseCors("EnableCORS");
........
}
这是 Angular POST 请求:
login(form: NgForm) {
let credentials = JSON.stringify(form.value);
console.log(credentials);
this.http.post("http://localhost:52008/Account/GetJWT", credentials, {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
})
}
POSTMAN 查询的结果
解决方案
You could configure the cores in startup.cs like below and add the origin to ConfigurationServices like below.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://example.com"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
Add the CORS policy to the specific action.
[HttpGet]
[EnableCors("AllowSpecificOrigin")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
Reference : Enable Cross-Origin Requests (CORS) in ASP.NET Core
推荐阅读
- excel - VBS - 如何获取文件名的今天日期?
- perl - 如何存储和检索 perl 对象
- linux - 记录 Bash 交互,分别保存 STDIN、STDOUT
- html - 仅在图标而不是名称上切换类别导航
- android - 单击 ActionBar 菜单项时带有 Android ActionBar 的弹出对话框
- javascript - 使用 Node.js 将 createWriteStream txt 内容写入全局变量
- r - 将 ifelse() 添加到 Map 函数中
- crystal-lang - 重新启动“琥珀表”时记录全部删除
- python - Raspberry Pi 距离传感器的追溯
- uwp - 使用 WritableBitmap 时抛出 ObjectDisposedException