我正在使用身份验证在 Blazor Webassembly 中测试 gRPC-Web,并遇到了一些关于如何干净地访问我的 gRPC 通道的问题。
没有身份验证,有一种非常简单和干净的方法,如 grpc-dotnet https://github.com/grpc/grpc-dotnet/tree/master/examples/Blazor的 Blazor 示例中所述。
提供渠道:
builder.Services.AddSingleton(services =>
{
// Get the service address from appsettings.json
var config = services.GetRequiredService<IConfiguration>();
var backendUrl = config["BackendUrl"];
var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler()));
var channel = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions { HttpClient = httpClient });
return channel;
});
Run Code Online (Sandbox Code Playgroud)
Razor 文件中的用法
@inject GrpcChannel Channel
Run Code Online (Sandbox Code Playgroud)
直接在 razor 文件中添加身份验证并创建通道也没有那么复杂
@inject IAccessTokenProvider AuthenticationService
...
@code {
...
var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler()));
var tokenResult = …Run Code Online (Sandbox Code Playgroud)