You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于.NET 7 C# 11实现gRPC网关路由模式的方法咨询

在.NET 7中实现gRPC网关路由服务

一、关于你拿到的代码说明

你提供的AddGrpcGateway方法并非.NET官方框架原生API,属于非官方或AI生成的虚构实现,因此无法查到相关技术资料。以下是基于.NET 7官方生态的标准实现方案。

二、分步实现方案

1. 安装必要NuGet包

使用官方反向代理库YARP来实现gRPC路由,需要安装以下包:

Install-Package Yarp.ReverseProxy
Install-Package Grpc.AspNetCore

2. 配置路由规则

在appsettings.json中添加路由与集群配置,匹配对应gRPC服务的请求路径:

{
  "ReverseProxy": {
    "Routes": {
      "books-grpc-route": {
        "ClusterId": "books-cluster",
        "Match": {
          "Path": "/bookstore.BookService/{**}"
        }
      },
      "users-grpc-route": {
        "ClusterId": "users-cluster",
        "Match": {
          "Path": "/user.UserService/{**}"
        }
      }
    },
    "Clusters": {
      "books-cluster": {
        "Destinations": {
          "books-destination": {
            "Address": "http://localhost:5001"
          }
        }
      },
      "users-cluster": {
        "Destinations": {
          "users-destination": {
            "Address": "http://localhost:5003"
          }
        }
      }
    }
  }
}

注:Path中的bookstore.BookService需与你的gRPC服务.proto文件中定义的完全限定服务名一致。

3. 注册并启用反向代理

在Program.cs中配置服务与中间件:

var builder = WebApplication.CreateBuilder(args);

// 注册YARP反向代理,加载配置文件中的路由规则
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

// 启用gRPC请求处理支持
builder.Services.AddGrpc();

var app = builder.Build();

// 启用反向代理中间件
app.MapReverseProxy();

app.Run();

4. 验证路由效果

  • 确保端口5001的books服务、端口5003的users服务正常运行
  • 启动网关服务后,客户端请求网关的/bookstore.BookService/[方法名]会被路由到books服务;请求/user.UserService/[方法名]会被路由到users服务

三、可选:自定义前缀路由

如果需要通过/books、/users这类前缀区分路由,可以用代码方式配置路由转换:

builder.Services.AddReverseProxy()
    .AddRoute("books-grpc-route", route =>
    {
        route.ClusterId = "books-cluster";
        route.Match.Path = "/books/{**}";
        // 转发前移除前缀
        route.Transforms.AddPathRemovePrefix("/books");
    })
    .AddCluster("books-cluster", cluster =>
    {
        cluster.Destinations.Add("books-destination", new DestinationAddress("http://localhost:5001"));
    })
    .AddRoute("users-grpc-route", route =>
    {
        route.ClusterId = "users-cluster";
        route.Match.Path = "/users/{**}";
        route.Transforms.AddPathRemovePrefix("/users");
    })
    .AddCluster("users-cluster", cluster =>
    {
        cluster.Destinations.Add("users-destination", new DestinationAddress("http://localhost:5003"));
    });

内容的提问来源于stack exchange,提问作者padavan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 06:00:30