【问题标题】:Can I combine a gRPC and webapi app into a .NET Core 3.0 in C#?我可以在 C# 中将 gRPC 和 webapi 应用程序组合到 .NET Core 3.0 中吗?
【发布时间】:2020-02-27 04:37:40
【问题描述】:

我正在使用 dot net core 3.0。

我有 gRPC 应用程序。我可以通过 gRPC 协议与之通信。

我认为我的下一步是添加一些宁静的 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();

        });
    }
}

还有我的控制器:

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

有什么想法吗?

谢谢

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

编辑:屏幕视图

【问题讨论】:

  • 你有 github repo 还是有完整代码的东西(比如你的 .csproj 和 BootNodeService 类)
  • @BurnsBA 当然。我在问题正文的底部添加了链接。
  • 您确定您的网络端口在端口 8001 上吗?看起来您的项目配置为 11837/44380 (http/https)。我克隆了您的项目并按 f5,浏览器自动加载 https://localhost:44380/admin 并显示“来自管理员的问候”
  • @BurnsBA 好的。谢谢。您是否偶然使用了 macOS?
  • 没有宏。 Visual Studio 2019,尽管它应该与 dotnet core 3 的任何 msbuild 工具构建相同

标签: c# rest .net-core grpc


【解决方案1】:

我找到了解决方案。我没有提到我在 MacOS 上运行并使用 Kestrel(看起来 MacOS 和 Kestrel 的组合是问题所在)。对于丢失的信息,我深表歉意。

解决方案类似于here。我必须为 webapi 端口添加对 options.ListenLocalhost 的调用。

代码如下:

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>();
            });
    }
}

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多