RestSharp 107+ 必须用 await 执行异步请求,禁用同步方法;需复用单例 RestClient 实例;GET 用 GetAsync 自动反序列化,POST 优先 AddJsonBody;调试先查原始响应体,注意字段映射与错误封装。

RestSharp 107+ 版本怎么发 GET 请求
新版 RestSharp(107.0+)彻底移除了同步方法,所有请求都必须用 await,直接调 Execute 或 ExecuteAsync 会编译报错或返回空响应。
常见错误现象:response.Data 为 null,但 response.StatusCode 是 200;或者抛出 NotSupportedException: Synchronous operations are disallowed。
- 必须用
await client.ExecuteAsync(request),不能用client.Execute(request) -
IRestRequest默认是 GET,不用显式设Method.Get - 查询参数用
request.AddQueryParameter("key", "value"),别拼在 URL 里(易编码错误) - 如果要反序列化 JSON 到对象,用
await client.GetAsync<t>(request)</t>更简洁,内部自动调JsonSerializer
var client = new RestClient("https://api.example.com");
var request = new RestRequest("users/{id}");
request.AddUrlSegment("id", "123");
var user = await client.GetAsync<User>(request); // 直接拿到反序列化对象POST JSON 数据时 body 总是空
不是加了 AddJsonBody 就万事大吉——RestSharp 107+ 默认 Content-Type 是 application/json,但某些 API(比如 ASP.NET Core Minimal API)对空 body 或缺失 Content-Length 很敏感。
容易踩的坑:用 request.AddBody(obj) 而不是 request.AddJsonBody(obj);或手动设了 request.AddParameter("application/json", json, ParameterType.RequestBody) 却忘了清空默认 body。
-
AddJsonBody会自动序列化并设好 header,优先用它 - 避免混用
AddBody和AddJsonBody,后者会覆盖前者 - 如果 API 返回 415(Unsupported Media Type),检查是否服务端没启用 JSON 输入格式(如 ASP.NET Core 缺少
AddJsonOptions) - 调试时可临时加
request.OnBeforeSerializing = req => Console.WriteLine(req.Body);看实际发了什么
如何复用 RestClient 提升性能
RestClient 是线程安全的,且内部管理连接池和 HttpClient 实例——但很多人每次请求都 new 一个,导致连接耗尽、DNS 重查、TLS 握手开销飙升。
典型症状:高并发下请求变慢、偶发 SocketException 或 TimeoutException,日志里出现大量 Connection refused 或 Unable to connect to the remote server。
- 全局只建一个
RestClient实例(比如注入到 DI 容器,生命周期设为 Singleton) - 不要在 using 块里创建
RestClient,它不实现IDisposable(107+ 已移除 Dispose) - 若需不同 base URL,用
new RestClient("https://other.api"),但别每个请求都 new - 超时等配置统一在构造时设好:
new RestClientOptions { MaxTimeout = 10_000 }
反序列化失败但 Status Code 是 200
RestSharp 不校验响应内容是否真能转成目标类型,GetAsync<t>()</t> 在 JSON 格式错、字段名不匹配、null 值没标注可空时,静默返回 default(T),而不是抛异常。
你看到 user.Name 是 null,user.Id 是 0,但没报错——大概率是 JSON 字段名和 C# 属性名对不上,或服务端返回了 error envelope(比如 {"success":false,"message":"xxx"})。
- 先用
await client.GetStringAsync(request)打印原始响应体,确认结构 - 字段映射用
[JsonPropertyName("user_name")](System.Text.Json)或[DataMember(Name = "user_name")](Newtonsoft) - 别假设服务端一定返回纯数据,加一层判断:
if (response.Content?.Contains("error") == true) throw new ApiException(response.Content); - 自定义序列化器时,确保
RestClientOptions.Serializer设置正确,否则AddJsonBody和GetAsync<t></t>可能用不同序列化逻辑
RestSharp 的坑多数藏在“默认行为”里:自动序列化、隐式 header、静默失败。越想省事写得越简短,越容易掉进连接复用、JSON 映射、异步陷阱这三类问题里。


















