0

I'm sending trailers from the server to the client, but on the client I can't access these trailers.

Server:

// 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);
    }
}

Client (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"));
}

It's entering the if. Trailer count is 0 when it should be 1.

Guilherme Molin
  • 308
  • 4
  • 13

1 Answers1

0

I found the answer. First we need to add CORS policy to the service:

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

Then expose the header (trailer) on the CORS policy:

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");
        });
}
Guilherme Molin
  • 308
  • 4
  • 13