How to access the HTTP request body using RestSharp?

Epoc picture Epoc · May 27, 2013 · Viewed 28.4k times · Source

I'm building a RESTful API client in C# .NET 3.5.

I first started building it with the good old HttpWebClient (and HttpWebResponse), I could do whatever I wanted with. I were happy. The only thing I was stuck on was the automatic deserialization from JSON response.

So, I've heard about a wonderful library called RestSharp (104.1) which eases the development of RESTful API clients, and automatically deserialize JSON and XML responses. I switched all my code on it, but now I realize I can't do things I could do with HttpWebClient and HttpWebResponse, like access and edit the raw request body.

Anyone has a solution ?

Edit : I know how to set the request body (with request.AddBody()), my problem is that I want to get this request body string , edit it, and re-set it in the request (updating the request body on the fly)

Answer

davmos picture davmos · May 27, 2013

The request body is a type of parameter. To add one, you can do one of these...

req.AddBody(body);
req.AddBody(body, xmlNamespace);
req.AddParameter("text/xml", body, ParameterType.RequestBody);
req.AddParameter("application/json", body, ParameterType.RequestBody);

To retrieve the body parameter you can look for items in the req.Parameters collection where the Type is equal to ParameterType.RequestBody.

See code for the RestRequest class here.

Here is what the RestSharp docs on ParameterType.RequestBody has to say:

If this parameter is set, it’s value will be sent as the body of the request. The name of the Parameter is ignored, and so are additional RequestBody Parameters – only 1 is accepted.

RequestBody only works on POST or PUT Requests, as only they actually send a body.

If you have GetOrPost parameters as well, they will overwrite the RequestBody – RestSharp will not combine them but it will instead throw the RequestBody parameter away.

For reading/updating the body parameter on-the-fly, you can try:

var body = req.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
if (body != null)
{
    Console.WriteLine("CurrentBody={0}", body.Value);
    body.Value = "NewBodyValue";
}

Or failing that, create a new copy of the RestRequest object with a different body.