NET5.0 Blazor WASM CORS 客户端异常 [英] NET5.0 Blazor WASM CORS client exception
问题描述
我有一个 Blazor WASM 应用程序和一个 Web Api,可以通过 HttpClient 由 Blzor 调用.这两个程序都在同一台机器上运行(并且也在生产环境中运行,这对于小型企业应用程序来说不应该是陌生的!).
I have a Blazor WASM app and a Web Api to get called by Blzor via HttpClient. Both programs run on the same machine (and also in production environment which should not be to exotic for a small business application!).
从 Blazor 客户端调用 Web Api 导致客户端 CORS 异常
Calling the Web Api from the Blazor client result in a client CORS exception
从源 'https://localhost:5001' 获取访问 'http://localhost:4040/' 已被 CORS 策略阻止:没有 'Access-Control-Allow-Origin' 标头存在于请求的资源.如果不透明响应满足您的需求,请将请求的模式设置为no-cors"以在禁用 CORS 的情况下获取资源.
Access to fetch at 'http://localhost:4040/' from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这是这种情况下的预期行为.
which is the expected behavior for this case.
在我用 PHP 开发的一个以前的 api 项目中,它具有相同的客户端行为,我可以通过简单地设置响应头来绕过 CORS 异常,例如
In an former api project I developed in PHP, that had the same client behavior, I can bypass the CORS exception by simply setting the response header e.g.
$response = new Response;
$response->setState(false, $route->command);
...
header("Access-Control-Allow-Origin: *");
echo $response;
现在我想在我的 .net 5.0 Web Api 中使用它.我在互联网上找到了不同的文档来处理
Now I want this in my .net 5.0 Web Api. I found different docs in the internet to cope with that like in
https://docs.microsoft.com/de-de/aspnet/core/security/cors?view=aspnetcore-5.0https://www.c-sharpcorner.com/article/enabling-cors-in-asp-net-core-api-application/https:///docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder.withorigins?view=aspnetcore-5.0
并在我的 api 中实现它
and implemented it in my api
public class Startup {
//---------------------------------------------------------------------
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
//---------------------------------------------------------------------
public IConfiguration Configuration { get; }
//---------------------------------------------------------------------
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices
(
IServiceCollection services
)
=> services
.AddCors()
.AddSwaggerGen(c => c.SwaggerDoc("v1", new OpenApiInfo { Title = "api", Version = "v1"}) )
.AddControllers()
;
//---------------------------------------------------------------------
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure
(
IApplicationBuilder app,
IWebHostEnvironment env
)
=> app.
apply( _ =>
{
if (true) //(env.IsDevelopment())
{
app
.UseDeveloperExceptionPage()
.UseSwagger()
.UseSwaggerUI( c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "api v1") );
}
})
.UseCors( cors =>
cors
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed( _ => true )
.AllowCredentials()
)
.UseHttpsRedirection()
.UseRouting()
.UseAuthorization()
.UseEndpoints( e => e.MapControllers() )
;
//---------------------------------------------------------------------
}
甚至尝试在 ApiController 中设置响应头
Even tried to set the Response Header in the ApiController
[Route("/")]
[ApiController]
public sealed class ServertimeController : ControllerBase
{
//[EnableCors("AllowOrigin")]
[HttpGet]
public Servertime Get() {
Response.Headers.Add("Access-Control-Allow-Origin", "*");
Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT");
return servertime();
}
}
Blazor WASM 客户端看起来像
The Blazor WASM client looks like
private async void onClick()
{
var response = await httpClient.GetFromJsonAsync<Servertime> ("http://localhost:4040");
message = response.servertime;
this.StateHasChanged();
}
但它仍然导致客户端 CORS 异常.为了绕过这个进行开发,我使用了浏览器扩展CORS Unblock",但这不是部署的选项.
But it still results in the client CORS exception. To bypass this for development I use the browser extension "CORS Unblock", but this is not an option for deployment.
避免 Blazor 客户端异常的正确方法是什么,我想念什么?
What would be the correct approach to avoid Blazor client exception, what do I miss?
推荐答案
@Dmitriy Grebennikov 的回答也是有效的,但需要稍微改进以使其更安全.
@Dmitriy Grebennikov answer is also valid but it needs a little bit improvements to make this more secure.
在Startup.cs
的ConfigureServices
中,在services.AddControllers();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://localhost:44338")
.AllowAnyMethod()
.AllowAnyHeader());
});
确保您的网址不应以 /
结尾.
Make sure that your url should not end with /
.
您可以将多个 url 传递给 WithOrigins
方法.最后在 Startup.cs
的 Configure
方法中,在 app.UseAuthorization();
之前和 app.UseRouting() 之后添加以下行);
You can pass many url to WithOrigins
method.
finally in the Configure
method of Startup.cs
add the following line before app.UseAuthorization();
and after app.UseRouting();
app.UseCors();
代码现在应该可以工作了.
The code should be working now.
这篇关于NET5.0 Blazor WASM CORS 客户端异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!