# Grpc.Core.RpcException：Status(StatusCode="InvalidArgument", Detail="无效消息长度：收到 1048577 字节，最大为 1048576。")

- **ID:** `dotnet/grpc-invalid-message-length`
- **领域:** dotnet
- **类别:** protocol_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

gRPC 请求或响应消息超过了服务器或客户端配置的最大大小限制，默认值为 1 MB（1048576 字节）。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Grpc.Core 2.46 | active | — | — |
| Grpc.Net.Client 2.52 | active | — | — |
| .NET 6.0 | active | — | — |
| .NET 7.0 | active | — | — |
| .NET 8.0 | active | — | — |

## 解决方案

1. ```
   在服务器端 Program.cs 中增加最大消息大小：services.AddGrpc(options => options.MaxReceiveMessageSize = 2 * 1024 * 1024); // 2 MB
   ```
2. ```
   在客户端设置 GrpcChannelOptions 上的 MaxReceiveMessageSize：var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions { MaxReceiveMessageSize = 2 * 1024 * 1024 });
   ```

## 无效尝试

- **** — This removes all size limits, potentially leading to memory exhaustion or denial-of-service attacks. (80% 失败率)
- **** — Compression reduces size but may not bring it under the limit if the original is too large; also requires server support. (60% 失败率)
