微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法访问客户端中的 RpcException 预告片

如何解决无法访问客户端中的 RpcException 预告片

我正在从服务器向客户端发送预告片,但在客户端上我无法访问这些预告片。

服务器:

// UserContract.cs
public Task<User> GetUserAsync(UserDto userDto,CallContext context = default)
{
    try
    {
        throw new NotImplementedException();
    }
    catch
    {
        Metadata Metadata = new Metadata { { "test","testvalue" } };
        throw new RpcException(new Status(StatusCode.Internal,"Error"),Metadata);
    }
}

客户(Blazor):

try
{
    await this.FactoryGrpc.CreateService<IUserContract>().GetUserAsync(userDto);
}
catch (RpcException exp)
{
    if (exp.Trailers.Count == 0)
    {
        this.Popup.ShowMessage("Where's the trailer?");
        return;
    }

    this.Popup.ShowMessage(exp.Trailers.GetValue("test"));
}

它正在输入 if。拖车计数应该是 1 时却是 0。

解决方法

我找到了答案。首先,我们需要向服务添加 CORS 策略:

https://docs.microsoft.com/pt-br/aspnet/core/grpc/browser?view=aspnetcore-5.0

然后在 CORS 策略上公开标题(预告片):

public void ConfigureServices(IServiceCollection services)
{
    // Add CORS (Cross-Origin Resource Sharing)
    services.AddCors(
        options => options.AddPolicy("AllowAll",builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .WithExposedHeaders("Grpc-Status","Grpc-Message","Grpc-Encoding","Grpc- Accept-Encoding","test");
        }));
}


public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
    app.UseCors();

    app.UseEndpoints(
        endpoints =>
        {
            endpoints.MapGrpcService<UsuarioContrato>().RequireCors("AllowAll");
        });
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。