Tra*_*try 2 c# cors asp.net-web-api2 .net-core
我正在构建 .Net 5 Web API,并且仅当我在本地(也称为本地主机)运行时才会遇到 CORS 问题。当我将应用程序部署到 Azure 后,我可以从 Blazor 应用程序正常访问我的 API。
类Startup.cs
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
Run Code Online (Sandbox Code Playgroud)
类:Startup.cs
方法:ConfigureServices
services.AddCors(options =>
{
//didn't work
//options.AddDefaultPolicy(builder =>
//{
// builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
//});
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://localhost:44373/", "https://myawesomesite")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
Run Code Online (Sandbox Code Playgroud)
类:Startup.cs
方法:Configure
app.UseCors(MyAllowSpecificOrigins);
Run Code Online (Sandbox Code Playgroud)
只需从本地主机 URL 中删除尾随的“/”,并且为了进行测试,您可以尝试删除 .AllowCredentials()。
并使用以下语法:
services.AddCors(o => o.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://localhost:44373",
"https://myawesomesite")
.AllowAnyMethod()
.AllowAnyHeader();
}));
Run Code Online (Sandbox Code Playgroud)
并且您的 UseCors 方法应该位于 UseRouting 和 UseAuthourization 之间
app.UseRouting()
....
.....
app.UseCors(MyAllowSpecificOrigins);
....
....
app.UseAuthorization(); // if you need the one
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8037 次 |
| 最近记录: |