我可以在 C# 中将 gRPC 和 webapi 应用程序组合到 .NET Core 3.0 中吗?

jus*_*mer 8 c# rest .net-core grpc

我正在使用 dot net core 3.0。

我有 gRPC 应用程序。我能够通过 gRPC 协议与它通信。

我认为我的下一步是添加一些 Restful API 支持。我修改了我的启动类以添加控制器、路由等......当我尝试使用浏览器导航到 API 时,无论我使用哪种协议 (http/https) 和端口,我都会收到错误“ERR_INVALID_HTTP_RESPONSE”。gRPC 应该使用 5001,而 webapi 应该使用 8001。

这是我的启动课程:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();

        app.UseRouting();
        app.UseHttpsRedirection();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGrpcService<BootNodeService>();
            endpoints.MapControllers();

        });
    }
}
Run Code Online (Sandbox Code Playgroud)

还有我的控制器:

[ApiController]
[Route("[controller]")] 
public class AdminController : ControllerBase 
{ 
    [HttpGet] public string Get() 
    { return "hello"; } 
}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

谢谢

编辑:整个项目可以在这个 repo 中找到。

编辑:屏幕视图 在此处输入图片说明

jus*_*mer 10

我找到了解决方案。我没有提到我在 MacOS 上运行并使用 Kestrel(似乎 MacOS 和 Kestrel 的组合是问题所在)。我为丢失的信息道歉。

解决方案类似于这里的内容。我不得不options.ListenLocalhost为 webapi 端口添加一个调用。

这是代码:

public class Program
{
    public static void Main(string[] args)
    {
       IHostBuilder hostBuilder = CreateHostBuilder(args);
       IHost host = hostBuilder.Build();
       host.Run();
    }

    // Additional configuration is required to successfully run gRPC on macOS.
    // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(options =>
                {
                    options.ListenLocalhost(5001, o => o.Protocols =
                        HttpProtocols.Http2);

                    // ADDED THIS LINE to fix the problem
                    options.ListenLocalhost(11837, o => o.Protocols =
                        HttpProtocols.Http1);
                });
                webBuilder.UseStartup<Startup>();
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢