4

I am looking for a way to access the serialized result of the AddBody call.

I am using the built in 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);
}
Nikoli
  • 147
  • 12

4 Answers4

2

I also struggled with this (using v107 preview) and couldn't find any examples of logging the actual string sent to the server. 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:

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}");
};
Rob Bird
  • 3,764
  • 2
  • 28
  • 38
  • Does the method I used no longer work in 107? request.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault(); – Nikoli Dec 24 '21 at 16:04
  • @Nikoli - yes it still works and thanks this is still a great way to get the request body as an object. But that can hide some types of issues - I was looking to see what the string value that gets sent over http looked like once serialised (using json.net etc) - so in my case I wanted to check that pascal case was being used and date formats when converting my object to json. – Rob Bird Dec 27 '21 at 20:04
  • Cannot resolve symbol 'OnBeforeRequest' – R-D Feb 22 '23 at 19:30
1

I figured it out by finding this post.

request.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault();
Community
  • 1
  • 1
Nikoli
  • 147
  • 12
0

RestSharp itself doesn't expose the serialized request body when you pass an object to it.

There is a way to get at it though, I just posted over here: https://stackoverflow.com/a/75537611/2509281

R-D
  • 566
  • 6
  • 13
-1

Right off the RestSharp homepage (http://restsharp.org/):

// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string <~~~~~~~~~~
1232133d2ffa
  • 191
  • 1
  • 13