RestSharp获得序列化输出
本文关键字:输出 序列化 RestSharp | 更新日期: 2023-09-27 18:07:38
我正在寻找一种方法来访问AddBody调用的序列化结果。
我正在使用内置的RestSharp序列化器。例子:
class Foo
{
public string FooField;
}
void SendRecord()
{
var f = new Foo();
f.FooField = "My Value";
request.AddBody(f);
// How do I get the serialized json result of the add body call without
// data? I would like to log the serialized output of the add body call to
// the database.
//Expected {"FooField":"My Value"}
var response = client.Execute(request);
}
我也为此而挣扎(使用v107预览版),找不到任何记录发送到服务器的实际字符串的示例。我试图调试的问题是获得正确的序列化设置,因此对象对我没有用处。
我能找到的唯一方法来获得序列化的主体作为一个字符串是挂钩到OnBeforeRequest事件的RestRequest:
var request = new RestRequest("/", Method.Post)
.AddHeader(KnownHeaders.ContentType, "application/json", false)
.AddJsonBody(myObj);
request.OnBeforeRequest = async (httpRequest) =>
{
var requestBodyStr = await httpRequest.Content.ReadAsStringAsync();
Trace.WriteLine($"Request body: {requestBodyStr}");
};
我发现了这篇文章。
request.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault();
RestSharp本身在向它传递对象时不会公开序列化的请求体。
有一种方法可以得到它,我只是在这里发布:https://stackoverflow.com/a/75537611/2509281
直接关闭RestSharp主页(http://restsharp.org/):
// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string <~~~~~~~~~~