gRPC走http2协议,到目前我还没找到如何把gRPC server 部署在iis下。
现在只能走Kestrel。
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); webBuilder.UseKestrel(); webBuilder.UseUrls("http://localhost:7777"); webBuilder.ConfigureKestrel(i => { i.ConfigureEndpointDefaults(op => { op.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2; }); }); });
或者 appsettings.json 可以配置协议为http2:
"Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:7777", "Protocols": "Http2" } } }
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); options.JsonSerializerOptions.Converters.Add(new DateTimeNullConverter()); }); services.AddGrpc(); services.AddMagicOnion(i => { i.IsReturnExceptionStackTraceInErrorDetail = true; i.SerializerOptions = MessagePackSerializerOptions.Standard.WithResolver( MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Instance); i.EnableCurrentContext = true; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); //app.UseAuthorization(); app.UseEndpoints(endpoints => { //endpoints.MapControllers(); endpoints.MapMagicOnionService(); }); } }
客户端调用:
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); var channel = GrpcChannel.ForAddress("http://localhost:7777"); var client = MagicOnionClient.Create<IUserSvc>(channel, MessagePackSerializerOptions.Standard.WithResolver( MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Instance)); var users = await client.GetUsrs();