Search code examples
c#restsharp

Read raw request body of RestRequest


I am using RestSharp a lot in my project, and I recently needed to implement a request authenticator that calculates a SHA256 hash of request body, and adds it into the Authorization request header. I came up with the following code:

public class HashAuthenticator : IAuthenticator
{
  public ValueTask Authenticate(IRestClient client, RestRequest request)
  {
     if (request.Parameters.Any(x => x.Type == ParameterType.RequestBody))
     {
         byte[] content = Encoding.UTF8.GetBytes(request.Parameters.First(x => x.Type == ParameterType.RequestBody).Value.ToString());
         if (content.Length > 0)
         {
               hash = Hash.SHA256(content);
               request.AddHeader("Authorization", hash);
         }
      }
  }
}

The above method of extracting request body works well when the original request body is JSON and it is constructed in the following way:

var request = new RestRequest("", Method.Post);
request.AddJsonBody(new { someKey = "value" });
// or request.AddParameter("application/json", "{ abc: xyz }", ParameterType.RequestBody)

However if I try to initialize a request with a x-www-form-urlencoded body like this:

// This approach is used to initialize requests with x-www-form-urlencoded content type
// and automatically encode param names and values
var request = new RestRequest("", Method.Post);
request.AddParameter("SomeKey", "SomeValue", ParameterType.GetOrPost);

Then the above approach does not work. Although the actual HTTP request gets sent with the expected x-www-form-urlencoded content type and the expected body SomeKey=SomeValue, the RestRequest object (that I use in the authenticator code) does not contain a parameter with ParameterType.RequestBody.

Is there a universal way that would allow me to extract the raw request body from RestRequest regardless of the way how I added body parameters to RestRequest?


Solution

  • The request content is built with this helper class: RequestContent.cs on RestSharp GitHub.

    Unfortunately for you, the Authenticator is called BEFORE this helper class is called. However, newer versions of RestSharp added interceptors that could help you calculate your required hash... See RestSharp Request OnBeforeRequest property on GitHub.

    You ought to be able to replace the Authorization header with whatever you need for this scenario.