Token导航 LogoToken导航

Agent Skill · 前端设计

dotnet-grpc(dotnet gRPC 命令行)

dotnet-grpc 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

dotnet-grpc 是前端设计类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在前端设计类的 10,216 个 Skill 里排第 7,232。

总安装 399周安装 16GitHub Stars 16下载 129核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:dotnet-grpc(dotnet gRPC 命令行)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/dotnet-grpc
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-grpc
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-grpc

这个 Skill 是做什么的

前端设计类 Skill 关注页面结构、视觉规范和组件写法,输出通常是可运行的界面代码。

用于处理 gRPC 全生命周期相关任务。dotnet-grpc 属于前端设计类 Skill,可作为该场景下的辅助能力补充。涵盖 .proto 定义、代码生成、ASP.NET Core 服务端实现及四种流模式。适合在需要构建或集成 gRPC 服务时使用。安装前建议确认宿主环境兼容性与网络访问权限。

注意:不覆盖源码生成器编写或 HTTP 客户端配置等边界内容。

来源仓库内路径:skills/dotnet-grpc

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-grpc;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

dotnet-grpc 怎么安装?

在终端执行 npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-grpc。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

dotnet-grpc 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

dotnet-grpc 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

dotnet-grpc 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

dotnet-grpc 用的人多吗?

公开数据是累计安装 399 次,近一周安装 16 次,下载 129 次,GitHub 16 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

dotnet-grpc 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理前端设计类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

前端设计类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
frontend-design

前端设计 · Codex、Claude

8,823,360126,072只读MIT通过
vercel-composition-patterns

Vercel 组合模式 · Codex、Claude

3,858,81625,893需要联网MIT通过
vercel-react-native-skills

Vercel React native skills 前端 · Codex、Claude

2,468,66425,878只读MIT通过
adapt

adapt 搜索 · Codex、Claude

2,027,04023,125操作浏览器未明确通过
bolder

bolder 分析 · Codex、Claude

2,004,28823,130只读未明确通过
dotnet-grpc

dotnet gRPC 命令行 · 本页

39916需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

dotnet-grpc

Full gRPC lifecycle for.NET applications. Covers .proto service definition, code generation, ASP.NET Core gRPC server implementation and endpoint hosting, Grpc.Net.Client client patterns, all four streaming patterns (unary, server streaming, client streaming, bidirectional streaming), authentication, load balancing, and health checks.

Out of scope: Source generator authoring patterns (incremental generator API, Roslyn syntax trees) -- see [skill:dotnet-csharp-source-generators]. HTTP client factory patterns and resilience pipeline configuration -- see [skill:dotnet-http-client] and [skill:dotnet-resilience]. Native AOT architecture and trimming strategies -- see [skill:dotnet-native-aot] for AOT compilation, [skill:dotnet-aot-architecture] for AOT-first design patterns, and [skill:dotnet-trimming] for trim-safe development.

Cross-references: [skill:dotnet-resilience] for retry/circuit-breaker on gRPC channels, [skill:dotnet-serialization] for Protobuf wire format details. See [skill:dotnet-integration-testing] for testing gRPC services.


Proto Definition and Code Generation

Project Setup

gRPC uses Protocol Buffers as its interface definition language. The Grpc.Tools package generates C# code from .proto files at build time.

Server project:

<ItemGroup>
  <PackageReference Include="Grpc.AspNetCore" Version="2.*" />
</ItemGroup>

<ItemGroup>
  <Protobuf Include="Protos\*.proto" GrpcServices="Server" />
</ItemGroup>

Client project:

<ItemGroup>
  <PackageReference Include="Google.Protobuf" Version="3.*" />
  <PackageReference Include="Grpc.Net.Client" Version="2.*" />
  <PackageReference Include="Grpc.Tools" Version="2.*" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
  <Protobuf Include="Protos\*.proto" GrpcServices="Client" />
</ItemGroup>

Shared contracts project (recommended for larger services):

<ItemGroup>
  <PackageReference Include="Google.Protobuf" Version="3.*" />
  <PackageReference Include="Grpc.Tools" Version="2.*" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
  <Protobuf Include="Protos\*.proto" GrpcServices="Both" />
</ItemGroup>

Proto File Definition

syntax = "proto3";

option csharp_namespace = "MyApp.Grpc";

package myapp;

import "google/protobuf/timestamp.proto";
import "google/protobuf/empty.proto";

// Service definition with all 4 streaming patterns
service OrderService {
  // Unary: single request, single response
  rpc GetOrder (GetOrderRequest) returns (OrderResponse);

  // Server streaming: single request, stream of responses
  rpc ListOrders (ListOrdersRequest) returns (stream OrderResponse);

  // Client streaming: stream of requests, single response
  rpc UploadOrders (stream CreateOrderRequest) returns (UploadOrdersResponse);

  // Bidirectional streaming: stream of requests, stream of responses
  rpc ProcessOrders (stream CreateOrderRequest) returns (stream OrderResponse);
}

message GetOrderRequest {
  int32 id = 1;
}

message ListOrdersRequest {
  string customer_id = 1;
  int32 page_size = 2;
  string page_token = 3;
}

message CreateOrderRequest {
  string customer_id = 1;
  repeated OrderItemMessage items = 2;
}

message OrderResponse {
  int32 id = 1;
  string customer_id = 2;
  repeated OrderItemMessage items = 3;
  google.protobuf.Timestamp created_at = 4;
}

message OrderItemMessage {
  string product_id = 1;
  int32 quantity = 2;
  double unit_price = 3;
}

message UploadOrdersResponse {
  int32 orders_created = 1;
}

Code-Gen Workflow

The Grpc.Tools package runs the Protobuf compiler (protoc) and C# gRPC plugin at build time. Generated files appear in obj/ and are included automatically:

  1. Add .proto files to the project via <Protobuf> items
  2. Set GrpcServices to Server, Client, or Both
  3. Build the project -- generated C# types and service stubs appear in obj/Debug/net10.0/Protos/
  4. Implement the generated abstract base class (server) or use the generated client class

The gRPC code-gen toolchain uses source generation to produce the C# stubs from .proto definitions. This is conceptually similar to [skill:dotnet-csharp-source-generators] but uses protoc rather than Roslyn incremental generators.


ASP.NET Core gRPC Server

Service Implementation

Implement the generated abstract base class:

using Grpc.Core;
using MyApp.Grpc;

public sealed class OrderGrpcService(
    OrderRepository repository,
    ILogger<OrderGrpcService> logger) : OrderService.OrderServiceBase
{
    // Unary
    public override async Task<OrderResponse> GetOrder(
        GetOrderRequest request,
        ServerCallContext context)
    {
        var order = await repository.GetByIdAsync(request.Id, context.CancellationToken);
        if (order is null)
        {
            throw new RpcException(new Status(StatusCode.NotFound,
                $"Order {request.Id} not found"));
        }

        return MapToResponse(order);
    }

    // Server streaming
    public override async Task ListOrders(
        ListOrdersRequest request,
        IServerStreamWriter<OrderResponse> responseStream,
        ServerCallContext context)
    {
        await foreach (var order in repository.ListByCustomerAsync(
            request.CustomerId, context.CancellationToken))
        {
            await responseStream.WriteAsync(MapToResponse(order),
                context.CancellationToken);
        }
    }

    // Client streaming
    public override async Task<UploadOrdersResponse> UploadOrders(
        IAsyncStreamReader<CreateOrderRequest> requestStream,
        ServerCallContext context)
    {
        var count = 0;
        await foreach (var request in requestStream.ReadAllAsync(
            context.CancellationToken))
        {
            await repository.CreateAsync(MapFromRequest(request),
                context.CancellationToken);
            count++;
        }

        return new UploadOrdersResponse { OrdersCreated = count };
    }

    // Bidirectional streaming
    public override async Task ProcessOrders(
        IAsyncStreamReader<CreateOrderRequest> requestStream,
        IServerStreamWriter<OrderResponse> responseStream,
        ServerCallContext context)
    {
        await foreach (var request in requestStream.ReadAllAsync(
            context.CancellationToken))
        {
            var order = await repository.CreateAsync(MapFromRequest(request),
                context.CancellationToken);
            await responseStream.WriteAsync(MapToResponse(order),
                context.CancellationToken);
        }
    }

    private static OrderResponse MapToResponse(Order order) =>
        new()
        {
            Id = order.Id,
            CustomerId = order.CustomerId,
            CreatedAt = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(
                order.CreatedAt)
        };

    private static Order MapFromRequest(CreateOrderRequest request) =>
        new()
        {
            CustomerId = request.CustomerId,
            Items = request.Items.Select(i => new OrderItem
            {
                ProductId = i.ProductId,
                Quantity = i.Quantity,
                UnitPrice = (decimal)i.UnitPrice
            }).ToList()
        };
}

Endpoint Hosting

Register gRPC services in the ASP.NET Core pipeline:

var builder = WebApplication.CreateBuilder(args);

// Add gRPC services
builder.Services.AddGrpc(options =>
{
    options.MaxReceiveMessageSize = 4 * 1024 * 1024; // 4 MB
    options.MaxSendMessageSize = 4 * 1024 * 1024;
    options.EnableDetailedErrors = builder.Environment.IsDevelopment();
});

var app = builder.Build();

// Map gRPC service endpoints
app.MapGrpcService<OrderGrpcService>();

app.Run();

gRPC Reflection (Development)

Enable gRPC reflection for tools like grpcurl and grpcui:

builder.Services.AddGrpc();
builder.Services.AddGrpcReflection();

var app = builder.Build();

app.MapGrpcService<OrderGrpcService>();

if (app.Environment.IsDevelopment())
{
    app.MapGrpcReflectionService();
}

Client Patterns with Grpc.Net.Client

Basic Client

using Grpc.Net.Client;
using MyApp.Grpc;

// Create a channel (reuse across calls -- channels are expensive to create)
using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new OrderService.OrderServiceClient(channel);

// Unary call
var response = await client.GetOrderAsync(
    new GetOrderRequest { Id = 42 });

DI-Registered Client with IHttpClientFactory

Register gRPC clients via IHttpClientFactory for connection pooling and resilience:

builder.Services
    .AddGrpcClient<OrderService.OrderServiceClient>(options =>
    {
        options.Address = new Uri("https://order-service:5001");
    })
    .ConfigureChannel(options =>
    {
        options.MaxReceiveMessageSize = 4 * 1024 * 1024;
    });

Apply resilience via [skill:dotnet-resilience]:

builder.Services
    .AddGrpcClient<OrderService.OrderServiceClient>(options =>
    {
        options.Address = new Uri("https://order-service:5001");
    })
    .AddStandardResilienceHandler();

Reading Server Streams

using var call = client.ListOrders(
    new ListOrdersRequest { CustomerId = "cust-123" });

await foreach (var order in call.ResponseStream.ReadAllAsync())
{
    Console.WriteLine($"Order {order.Id}: {order.CustomerId}");
}

Client Streaming

using var call = client.UploadOrders();

foreach (var order in ordersToCreate)
{
    await call.RequestStream.WriteAsync(new CreateOrderRequest
    {
        CustomerId = order.CustomerId
    });
}

// Signal completion
await call.RequestStream.CompleteAsync();

// Read the response
var response = await call;
Console.WriteLine($"Created {response.OrdersCreated} orders");

Bidirectional Streaming

using var call = client.ProcessOrders();

// Start reading responses in background
var readTask = Task.Run(async () =>
{
    await foreach (var response in call.ResponseStream.ReadAllAsync())
    {
        Console.WriteLine($"Processed order {response.Id}");
    }
});

// Send requests
foreach (var order in ordersToProcess)
{
    await call.RequestStream.WriteAsync(new CreateOrderRequest
    {
        CustomerId = order.CustomerId
    });
}

await call.RequestStream.CompleteAsync();
await readTask;

Streaming Patterns Summary

gRPC supports four communication patterns:

PatternRequestResponseUse Case
UnarySingle messageSingle messageStandard request-response (CRUD, queries)
Server streamingSingle messageStream of messagesReal-time feeds, large result sets, push notifications
Client streamingStream of messagesSingle messageBulk uploads, aggregation, telemetry ingestion
Bidirectional streamingStream of messagesStream of messagesChat, real-time collaboration, event processing

Authentication

Bearer Token (JWT)

Server-side authentication:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://identity.example.com";
        options.TokenValidationParameters.ValidAudience = "order-api";
    });

builder.Services.AddAuthorization();
builder.Services.AddGrpc();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGrpcService<OrderGrpcService>().RequireAuthorization();

Client-side token propagation:

builder.Services
    .AddGrpcClient<OrderService.OrderServiceClient>(options =>
    {
        options.Address = new Uri("https://order-service:5001");
    })
    .AddCallCredentials(async (context, metadata, serviceProvider) =>
    {
        var tokenProvider = serviceProvider.GetRequiredService<ITokenProvider>();
        var token = await tokenProvider.GetTokenAsync(context.CancellationToken);
        metadata.Add("Authorization", $"Bearer {token}");
    });

Certificate Authentication (mTLS)

For service-to-service authentication with mutual TLS:

// Server: require client certificates
builder.WebHost.ConfigureKestrel(kestrel =>
{
    kestrel.ConfigureHttpsDefaults(https =>
    {
        https.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
    });
});

builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
    .AddCertificate(options =>
    {
        options.AllowedCertificateTypes = CertificateTypes.Chained;
        options.RevocationMode = X509RevocationMode.NoCheck; // Configure per environment
    });
// Client: provide client certificate
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(
    new X509Certificate2("client.pfx", "password"));

using var channel = GrpcChannel.ForAddress("https://order-service:5001",
    new GrpcChannelOptions
    {
        HttpHandler = handler
    });

Load Balancing

Client-Side Load Balancing

gRPC supports client-side load balancing with service discovery:

// DNS-based service discovery with round-robin
builder.Services
    .AddGrpcClient<OrderService.OrderServiceClient>(options =>
    {
        options.Address = new Uri("dns:///order-service:5001");
    })
    .ConfigureChannel(options =>
    {
        options.Credentials = ChannelCredentials.Insecure;
        options.ServiceConfig = new ServiceConfig
        {
            LoadBalancingConfigs = { new RoundRobinConfig() }
        };
    });

Proxy-Based Load Balancing

For environments with a load balancer (e.g., Kubernetes, Envoy, YARP):

  • Use L7 (HTTP/2-aware) load balancers -- L4 load balancers route at the TCP level and pin all gRPC requests to a single backend because HTTP/2 multiplexes on a single connection.
  • Envoy, Linkerd, and Kubernetes ingress controllers with gRPC support distribute requests at the RPC level.
  • Configure SocketsHttpHandler.EnableMultipleHttp2Connections = true to allow multiple connections when behind a proxy:
builder.Services
    .AddGrpcClient<OrderService.OrderServiceClient>(options =>
    {
        options.Address = new Uri("https://order-service-lb:5001");
    })
    .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
    {
        EnableMultipleHttp2Connections = true
    });

Health Checks

gRPC Health Check Protocol

Implement the standard gRPC health checking protocol (grpc.health.v1.Health) so orchestrators and load balancers can probe service status:

builder.Services.AddGrpc();
builder.Services.AddGrpcHealthChecks()
    .AddCheck("database", () =>
    {
        // Custom health check logic
        return HealthCheckResult.Healthy();
    });

var app = builder.Build();

app.MapGrpcService<OrderGrpcService>();
app.MapGrpcHealthChecksService();

Integration with ASP.NET Core Health Checks

gRPC health checks integrate with the standard ASP.NET Core health check system:

builder.Services.AddHealthChecks()
    .AddNpgSql(
        builder.Configuration.GetConnectionString("OrderDb")!,
        name: "order-db",
        tags: ["ready"]);

builder.Services.AddGrpc();
builder.Services.AddGrpcHealthChecks()
    .AddAsyncCheck("order-db", async (sp, ct) =>
    {
        var healthCheckService = sp.GetRequiredService<HealthCheckService>();
        var report = await healthCheckService.CheckHealthAsync(
            r => r.Tags.Contains("ready"), ct);
        return report.Status == HealthStatus.Healthy
            ? HealthCheckResult.Healthy()
            : HealthCheckResult.Unhealthy();
    });

Kubernetes Probes for gRPC

# Use grpc health check probe (Kubernetes 1.24+)
livenessProbe:
  grpc:
    port: 5001
  initialDelaySeconds: 10
  periodSeconds: 15

readinessProbe:
  grpc:
    port: 5001
  initialDelaySeconds: 5
  periodSeconds: 10

Interceptors

gRPC interceptors are middleware for gRPC calls, analogous to ASP.NET Core middleware or HTTP DelegatingHandlers.

Server Interceptor

public sealed class LoggingInterceptor(ILogger<LoggingInterceptor> logger)
    : Interceptor
{
    public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
        TRequest request,
        ServerCallContext context,
        UnaryServerMethod<TRequest, TResponse> continuation)
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            var response = await continuation(request, context);
            logger.LogInformation(
                "gRPC {Method} completed in {ElapsedMs}ms",
                context.Method, stopwatch.ElapsedMilliseconds);
            return response;
        }
        catch (RpcException ex)
        {
            logger.LogError(ex,
                "gRPC {Method} failed with {StatusCode}",
                context.Method, ex.StatusCode);
            throw;
        }
    }
}

// Register
builder.Services.AddGrpc(options =>
{
    options.Interceptors.Add<LoggingInterceptor>();
});

Client Interceptor

public sealed class AuthInterceptor(ITokenProvider tokenProvider) : Interceptor
{
    public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(
        TRequest request,
        ClientInterceptorContext<TRequest, TResponse> context,
        AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
    {
        var token = tokenProvider.GetCachedToken();
        var headers = context.Options.Headers ?? new Metadata();
        headers.Add("Authorization", $"Bearer {token}");

        var newContext = new ClientInterceptorContext<TRequest, TResponse>(
            context.Method, context.Host,
            context.Options.WithHeaders(headers));

        return continuation(request, newContext);
    }
}

Error Handling

Status Codes

Map domain errors to gRPC status codes:

gRPC StatusHTTP EquivalentUse When
OK200Success
NotFound404Resource does not exist
InvalidArgument400Client sent bad data
PermissionDenied403Caller lacks permission
Unauthenticated401No valid credentials
AlreadyExists409Duplicate creation attempt
ResourceExhausted429Rate limited
Internal500Unhandled server error
Unavailable503Transient failure -- safe to retry
DeadlineExceeded504Operation timed out

Rich Error Details

// Server: throw with metadata
var status = new Status(StatusCode.InvalidArgument, "Validation failed");
var metadata = new Metadata
{
    { "field", "customer_id" },
    { "reason", "Customer ID is required" }
};
throw new RpcException(status, metadata);

// Client: read error metadata
try
{
    var response = await client.GetOrderAsync(request);
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.InvalidArgument)
{
    var field = ex.Trailers.GetValue("field");
    var reason = ex.Trailers.GetValue("reason");
    logger.LogWarning("Validation error on {Field}: {Reason}", field, reason);
}

Deadlines and Cancellation

Always set deadlines on gRPC calls to prevent indefinite waits:

// Client: set a deadline
var deadline = DateTime.UtcNow.AddSeconds(10);
var response = await client.GetOrderAsync(
    new GetOrderRequest { Id = 42 },
    deadline: deadline);

// Server: check deadline and propagate cancellation
public override async Task<OrderResponse> GetOrder(
    GetOrderRequest request,
    ServerCallContext context)
{
    // context.CancellationToken is automatically cancelled when deadline expires
    var order = await repository.GetByIdAsync(request.Id, context.CancellationToken);
    // ...
}

gRPC-Web for Browser Clients

Browsers do not support HTTP/2 trailers required by native gRPC. gRPC-Web is a protocol variant that works over HTTP/1.1 and HTTP/2 without trailers, enabling browser JavaScript clients to call gRPC services.

Server Configuration

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddGrpc();
builder.Services.AddCors(options =>
{
    options.AddPolicy("GrpcWeb", policy =>
    {
        policy.WithOrigins("https://app.example.com")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding");
    });
});

var app = builder.Build();

app.UseRouting();
app.UseCors();
app.UseGrpcWeb(); // Must be between UseRouting and MapGrpcService

app.MapGrpcService<OrderGrpcService>()
    .EnableGrpcWeb()
    .RequireCors("GrpcWeb");

JavaScript Client (grpc-web)

// Using @improbable-eng/grpc-web or grpc-web package
import { OrderServiceClient } from './generated/order_grpc_web_pb';
import { GetOrderRequest } from './generated/order_pb';

const client = new OrderServiceClient('https://api.example.com');

const request = new GetOrderRequest();
request.setId(42);

client.getOrder(request, {}, (err, response) => {
    if (err) {
        console.error('gRPC error:', err.message);
        return;
    }
    console.log('Order:', response.toObject());
});

Envoy Proxy Alternative

Instead of ASP.NET Core gRPC-Web middleware, you can use an Envoy proxy to translate gRPC-Web requests to native gRPC. This is useful when the gRPC service cannot be modified:

# Envoy filter configuration
http_filters:
  - name: envoy.filters.http.grpc_web
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.filters.http.grpc_web.v3.GrpcWeb
  - name: envoy.filters.http.cors
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors
  - name: envoy.filters.http.router
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router

gRPC-Web Limitations

  • Unary and server streaming only -- client streaming and bidirectional streaming are not supported by gRPC-Web
  • No HTTP/2 trailers -- status and trailing metadata are encoded in the response body
  • CORS required -- cross-origin requests need explicit CORS configuration on the server
  • Consider SignalR for full-duplex browser communication -- see [skill:dotnet-realtime-communication] for alternatives when bidirectional streaming is required

Key Principles

  • Use .proto files as the contract -- they are the single source of truth for the API shape, shared between client and server
  • Set GrpcServices on <Protobuf> items -- Server for service projects, Client for consumer projects, Both for shared contracts
  • Reuse channels -- GrpcChannel manages HTTP/2 connections; creating a new channel per call wastes resources
  • Register gRPC clients via DI -- AddGrpcClient integrates with IHttpClientFactory for connection pooling and resilience
  • Always set deadlines -- calls without deadlines can hang indefinitely if the server is slow or unreachable
  • Use L7 load balancers -- L4 load balancers pin all traffic to one backend because HTTP/2 multiplexes on a single TCP connection
  • Implement the gRPC health check protocol -- enables Kubernetes probes and load balancers to monitor service health
  • Use gRPC-Web for browser clients -- native gRPC requires HTTP/2 trailers which browsers do not support; gRPC-Web bridges this gap

See [skill:dotnet-native-aot] for Native AOT compilation pipeline and [skill:dotnet-aot-architecture] for AOT-compatible patterns when building gRPC services with ahead-of-time compilation.


Agent Gotchas

  1. Do not create a new GrpcChannel per request -- channels are expensive to create and manage HTTP/2 connections. Reuse them or use DI-registered clients.
  2. Do not omit GrpcServices on <Protobuf> items -- the default is Both, which generates server and client stubs. This bloats client projects with unused server code and vice versa.
  3. Do not use L4 load balancers for gRPC without enabling EnableMultipleHttp2Connections -- HTTP/2 multiplexing means a single connection handles all RPCs, defeating load distribution.
  4. Do not throw generic Exception from gRPC services -- throw RpcException with appropriate StatusCode and descriptive messages. Unhandled exceptions become StatusCode.Internal with no useful detail.
  5. Do not forget to call CompleteAsync() on client streams -- the server waits for stream completion before sending its response. Forgetting this causes the call to hang.
  6. Do not use grpc.health.v1.Health without registering health checks -- an empty health service always reports Serving, which defeats the purpose of health monitoring.
  7. Do not enable gRPC-Web globally without CORS -- UseGrpcWeb() without a CORS policy allows any origin to call your gRPC services. Always pair with explicit RequireCors().
  8. Do not attempt client streaming or bidirectional streaming with gRPC-Web -- the gRPC-Web protocol only supports unary and server streaming. Use SignalR or native gRPC for full-duplex browser communication.

Attribution

Adapted from Aaronontheweb/dotnet-skills (MIT license).


References

平台分布

Codex

39.73%
按下载量换算51

Claude

27.59%
按下载量换算36

Cursor

18.36%
按下载量换算24

Gemini CLI

8.97%
按下载量换算12

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills