写在前面
本文介绍如何配置现有 ASP.NET Core gRPC 服务,以便使用 gRPC-Web 协议的浏览器应用也可调用。配置 gRPC-Web 后将允许浏览器中的JavaScript 和 Blazor 应用调用 gRPC 服务。
在上一篇的基础上,给服务端和客户端分别安装拓展包,Grpc.AspNetCore.Web
代码实现
配置加在服务端
using Grpc.Core;
using GrpcGreeter;
using static GrpcGreeter.Greeter;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddGrpc();
// 添加跨域配置
builder.Services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
}));
var app = builder.Build();
app.UseGrpcWeb();
app.UseCors();
// Configure the HTTP request pipeline.
app.MapGrpcService<GreeterService>().EnableGrpcWeb().RequireCors("AllowAll");
app.MapGet("/", () => "This gRPC service is gRPC-Web enabled, CORS enabled, and is callable from browser apps uisng the gRPC-Web protocal");
app.Run();
重点是以下4行代码
// 添加跨域配置
builder.Services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
}));
app.UseGrpcWeb();
app.UseCors();
app.MapGrpcService<GreeterService>().EnableGrpcWeb().RequireCors("AllowAll");
为了同时兼容Http1.1和 Http2,对appsettings.json也加了一点配置
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1AndHttp2"
}
}
}
测试的客户端部分加上了支持GrpcWeb的管道配置选项
using var channel = GrpcChannel.ForAddress("https://localhost:7086", (new GrpcChannelOptions()
{
HttpHandler = new GrpcWebHandler(new HttpClientHandler()),
UnsafeUseInsecureChannelCallCredentials = true
}));
调用示例
后续准备做个用Nodejs实现的浏览器应用来调用的客户端示例,验证一下流程。