gpt4 book ai didi

c# - NET5.0 Blazor WASM CORS 客户端异常

转载 作者:行者123 更新时间:2023-12-03 16:19:59 25 4
gpt4 key购买 nike

我有一个 Blazor WASM 应用程序和一个 Web Api,可以通过 HttpClient 由 Blzor 调用。这两个程序都运行在同一台机器上(并且也在生产环境中运行,这对于小型企业应用程序来说不应该是陌生的!)。
从 Blazor 客户端调用 Web Api 导致客户端 CORS 异常
从源 'https://localhost:5001' 访问 'http://localhost:4040/' 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' header 。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
这是这种情况下的预期行为。
在我用 PHP 开发的一个以前的 api 项目中,它具有相同的客户端行为,我可以通过简单地设置响应头来绕过 CORS 异常,例如

$response = new Response;
$response->setState(false, $route->command);
...
header("Access-Control-Allow-Origin: *");
echo $response;
现在我想在我的 .net 5.0 Web Api 中使用它。我在互联网上找到了不同的文档来解决这个问题
https://docs.microsoft.com/de-de/aspnet/core/security/cors?view=aspnetcore-5.0
https://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 中实现它
    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 中设置响应头
    [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 客户端看起来像
    private async void onClick()
{

var response = await httpClient.GetFromJsonAsync<Servertime> ("http://localhost:4040");
message = response.servertime;
this.StateHasChanged();
}
但它仍然导致客户端 CORS 异常。
为了绕过这个进行开发,我使用浏览器扩展“CORS Unblock”,但这不是部署的选项。
避免 Blazor 客户端异常的正确方法是什么,
我想念什么?

最佳答案

@Dmitriy Grebennikov 的回答也是有效的,但需要一些改进才能使其更安全。
ConfigureServicesStartup.csservices.AddControllers();前添加以下代码

services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://localhost:44338")
.AllowAnyMethod()
.AllowAnyHeader());
});
确保您的网址不应以 / 结尾.

您可以将多个 url 传递给 WithOrigins方法。
终于在 Configure Startup.cs的方法在 app.UseAuthorization(); 之前添加以下行之后 app.UseRouting();
app.UseCors();
代码现在应该可以工作了。

关于c# - NET5.0 Blazor WASM CORS 客户端异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64858434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com