我正在尝试创建一个Blazor WASM应用程序,该应用程序将使用GRPC调用grpc网关。
网关服务的说明如下:
syntax = "proto3";
import "Services/AdService.proto";
package BonnieAndClydesdale.Core;
service GatewayService {
rpc GetAds (AdRequest) returns (AdReply);
}我跟随本指南在服务器和客户端上建立grpc。
我的服务器的program.cs中有这样的内容:
builder.Services.AddGrpc();
builder.Services.AddGrpcReflection();
builder.Services.AddGrpcClient<AdService.AdServiceClient>(o => o.Address = new("https://localhost:7223")); // Downstream GRPC service
WebApplication app = builder.Build();
// Configure the HTTP request pipeline.
app.MapGrpcService<GatewayService>().EnableGrpcWeb();
app.UseGrpcWeb();在我的blazor应用程序的program.cs中:
builder.Services.AddSingleton(services =>
{
HttpClient httpClient = new(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
string baseUri = "https://localhost:7080"; // TODO - Add to AppSettings
GrpcChannel channel = GrpcChannel.ForAddress(baseUri, new() { HttpClient = httpClient });
return new GatewayService.GatewayServiceClient(channel);
});但是,当我加载此页面时:
public partial class ForSale: ComponentBase
{
[Inject]
private GatewayService.GatewayServiceClient Client { get; init; } = null!;//TODO replace with service
private readonly List<AdDetails> _ads;
public ForSale()
{
_ads = new();
}
protected override async Task OnInitializedAsync()
{
AdReply? rep = await Client.GetAdsAsync(new());
if (rep.AdDetails is not null)
{
_ads.AddRange(rep.AdDetails);
}
}
}我收到了一个CORS错误:
从源“https://localhost:7080/BonnieAndClydesdale.Core.GatewayService/GetAds”获取“https://localhost:5001”的访问已被CORS策略阻止:对飞行前请求的响应不通过访问控制检查:请求资源上不存在“访问控制-允许-原产地”报头。如果不透明响应满足您的需要,请将请求的模式设置为“no- CORS”,以获取禁用CORS的资源。
对如何解决这个问题有什么想法吗?
编辑
我看到了很多类似问题的答案,这些问题建议使用services.AddCors(...)和app.UseCors(),但这些方法似乎并不存在于Blazor应用程序中。
发布于 2022-05-13 13:24:39
这一问题源于对需要在何处制定CORS政策的误解。它需要在网关服务器上设置,而不是在Blazor应用程序上设置。这是有意义的,因为CORS是在服务器上实现的,但是出现了混淆,因为大多数教程似乎都假定我们使用的是Blazor。
为了完整起见,我将其添加到网关的startup.cs中(而不是Blazor )。
const string corsPolicy = "_corsPolicy";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: corsPolicy,
policy =>
{
policy.WithOrigins("https://localhost:5001",
"http://localhost:5000")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
WebApplication app = builder.Build();
app.UseCors(corsPolicy);https://stackoverflow.com/questions/72222696
复制相似问题