RestSharp请求对象无法在每次调用时重置的问题排查
问题修复:RestRequest循环调用时残留旧数据
问题根源
你的RestClientService把_restRequest声明为类级别的只读字段,仅在构造函数初始化一次。每次调用SendComment时,都是在同一个RestRequest实例上修改配置、添加JsonBody——而AddJsonBody方法会将新内容追加到请求体中,不会清空旧数据。
虽然你把RestClientService注册为Transient,但在CreateSendCommentJob方法中,整个循环复用的是同一个_restClientService实例(DI的Transient是每次解析时创建新实例,但这里你是一次性拿到实例后循环调用),所以_restRequest并不会重新初始化,导致旧数据残留。
修复方案
直接在每次调用SendComment时创建新的RestRequest实例,确保每次请求都是全新的请求对象,彻底避免旧数据干扰。
修改后的RestClientService代码:
public class RestClientService : IRestClientService { protected readonly RestClient _restClient; public RestClientService() { _restClient = new RestClient(); } public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId) { if (await IsPostExist(postId, website)) { // 每次调用创建全新的RestRequest var restRequest = new RestRequest(); _restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/"); restRequest.Method = Method.Post; restRequest.RequestFormat = DataFormat.Json; restRequest.AddJsonBody(new { post = postId, author_name = comment.Author, content = comment.Body }); var result = await _restClient.ExecuteAsync(restRequest); return new MessageDTO { Message = result.Content, Status = result.StatusCode.ToString() }; } return new MessageDTO { Message = "Post Not Found", Status = "404" }; } }
额外优化
可以直接在RestRequest初始化时指定完整请求URL,避免修改RestClient的全局BaseUrl,减少后续请求的潜在干扰:
// 替换原BaseUrl设置和RestRequest初始化逻辑 var requestUrl = $"{website.Url}/wp-json/wp/v2/comments/"; var restRequest = new RestRequest(requestUrl, Method.Post); restRequest.RequestFormat = DataFormat.Json; restRequest.AddJsonBody(new { post = postId, author_name = comment.Author, content = comment.Body }); var result = await _restClient.ExecuteAsync(restRequest);
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

