.net core中Grpc使用报错:Request protocol 'HTTP/1.1' is not supported.
阅读原文时间:2022年04月15日阅读:1

  显然这个报错是说HTTP/1.1不支持。

  首先,我们要知道,Grpc是Google开源的,跨语言的,高性能的远程过程调用框架,它是以HTTP/2作为通信协议的,所以当我启动启用一个服务作为Grpc的服务端(被调用方)时,我们需要将监听的端口设置成HTTP/2协议的,设置方法有两种:

  1、修改appsettings.json 

  在根节点下添加下面的配置

"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http2"
}
}

  需要注意的是,这个配置是修改默认行为,就是说修改所有端口的监听默认采用Http2(原来默认是Http1),但有时我们的项目是会监听多个端口,并不一定全是Http2协议。

  2、手动监听Kestrel端口

  修改Program中的CreateHostBuilder方法:  

public static IHostBuilder CreateHostBuilder(string\[\] args) =>  
    Host.CreateDefaultBuilder(args)  
        .ConfigureWebHostDefaults(webBuilder =>  
        {  
            webBuilder.ConfigureKestrel(options =>  
            {  
                options.ListenAnyIP(5000, listenOptions =>  
                {  
                    listenOptions.Protocols = HttpProtocols.Http2;  
                });  
            });  
            webBuilder.UseStartup<Startup>();  
        });

  其中使用ConfigureKestrel配置端口和它使用的协议,如果需要监听多个端口,只需要在使用ListenAnyIP方法监听即可,这样就无需改变默认协议了。

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章