简体   繁体   English

RestSharp 获取序列化输出

[英]RestSharp get serialized output

I am looking for a way to access the serialized result of the AddBody call.我正在寻找一种方法来访问 AddBody 调用的序列化结果。

I am using the built in RestSharp Serializer.我正在使用内置的 RestSharp Serializer。 Example:例子:

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);
}

我通过找到这篇文章弄清楚了。

request.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault();

I also struggled with this (using v107 preview) and couldn't find any examples of logging the actual string sent to the server.我也为此苦苦挣扎(使用 v107 预览版)并且找不到任何记录发送到服务器的实际字符串的示例。 The issue I was trying to debug was getting the right serialisation settings so the object was no use to me.我试图调试的问题是获得正确的序列化设置,因此该对象对我没有用。

The only way I could find to get the serialized body as a string was to hook into the OnBeforeRequest event on the RestRequest:我能找到将序列化主体作为字符串获取的唯一方法是挂接到 RestRequest 上的 OnBeforeRequest 事件:

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}");
};

Right off the RestSharp homepage ( http://restsharp.org/ ): 紧靠RestSharp主页( http://restsharp.org/ ):

// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string <~~~~~~~~~~

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM