3

I am calling an API that requires an MD5 hash of the body of the request in the request's header.

I am using RestSharp to send the requests. Normally I can check the Request.Parameters for the Body parameter and hash the value of the parameter before calling Execute.

Although, after calling AddFile the body parameter is empty and appears to stay empty until the content is prepared before sending the request. (Since files are stored separately)

Is there anyway to read the body content of the RestRequest after the multipart string has been generated but before the request is sent so I can add the MD5 hash to the header of the request?

lionpants
  • 1,469
  • 14
  • 24

3 Answers3

1

I realize this is an old question but I think the library handles this for you by allowing you access to the Http object before sending the request.

var client = new RestSharp.RestClient();

var request = new RestRequest();

request.OnBeforeRequest = (http) => {
    http.Headers.Add(new HttpHeader {
        Name = "CONTENT_MD5",
        Value = GenerateMd5Hash(x.RequestBody)
    });
}
ewahner
  • 1,149
  • 2
  • 11
  • 23
0

From additional research I have done, it appears that at this time there is not a way to achieve the functionality that I was after with the default API.

I ended up downloading the source code and added an event handler to the Http class that is now triggered before the HttpWebRequest is sent. I send the HttpWebRequest in the parameters of the event handler which is then bubbled all the way up to the RestClient.

I can then intercept the request in the top level code and add to the headers as I please before the request is sent.

This is probably not the most efficient modification but it works well enough for unit tests.

lionpants
  • 1,469
  • 14
  • 24
0

Unfortunately RestSharp doesn't naturally expose the serialized request body, if you pass an object to it. For example:

restRequest.AddXmlBody(myObject);

But it is possible to get at the raw request by basically recreating the same serializer that RestSharp uses and then serializing it on your own. As an example, say you are using restClient.UseDotNetXmlSerializer(), you could:

var dotNetXmlSerializer = new DotNetXmlSerializer();
var requestSerializer = new XmlRestSerializer().WithXmlSerializer(dotNetXmlSerializer);

Which is just a trimmed down version of what's in RestSharp's source code for UseDotNetXmlSerializer(). Then you just call this to get the raw request body:

var xmlRequestBody = requestSerializer.Serialize(myObject);

This code can be put anywhere that has access to myObject and is independent of your restClient. Basically what you're doing is leveraging the RestSharp namespaces to do an independent serialization.

R-D
  • 566
  • 6
  • 13