如何预览JsonContent生成的JSON字符串?API请求排障求助
预览JsonContent生成的JSON字符串方法
调用外部API时收到错误响应,但用Postman发送相同数据能得到正确结果,推测问题出在JsonContent生成的JSON内容上,以下是几种查看它生成的JSON字符串的方法:
相关代码
public async Task<ResponseDto> UploadAsync(RequestDto model, CancellationToken cancellationToken) { var requestUri = HttpHelper.BuildUri(uri.UPLOAD); JsonContent content = JsonContent.Create(model); // <= 需要查看这里生成的JSON内容 /* 后续请求代码暂时注释 var response = await _client.PostAsync(requestUri, content, cancellationToken); string responseContent = await response.Content.ReadAsStringAsync(cancellationToken); return JsonSerializer.Deserialize<ResponseDto>(responseContent) ?? throw new HttpRequestException(responseContent);*/ }
具体解决方案
1. 克隆后读取(不影响后续请求)
JsonContent继承自HttpContent,而HttpContent只能被读取一次,所以如果还要用原content发送请求,必须先克隆一份再读取内容:
// 克隆原JsonContent,避免消耗原内容 var clonedContent = await content.CloneAsync(cancellationToken); string generatedJson = await clonedContent.ReadAsStringAsync(cancellationToken); Console.WriteLine(generatedJson); // 输出预览JSON
2. 手动序列化对比
JsonContent.Create默认使用System.Text.Json进行序列化,所以可以直接手动序列化model得到相同的JSON字符串,同时也可以用这个字符串创建StringContent来测试请求:
string generatedJson = JsonSerializer.Serialize(model); Console.WriteLine(generatedJson); // 可选:用手动生成的JSON创建请求内容测试 var testContent = new StringContent(generatedJson, Encoding.UTF8, "application/json"); // 后续可以用testContent代替原content发送请求验证
3. 调试器查看私有字段(不推荐)
在调试模式下,可以查看JsonContent的私有_serializedContent字段(.NET 6及以上版本),但这种方式依赖框架内部实现,版本更新后可能失效,不推荐作为常规手段。
内容的提问来源于stack exchange,提问作者TryHard
相关产品推荐
相关产品推荐

