Developing Your Own Handlers

It’s trival to extend RestClient by using HttpClient DelegatingHandlers. I’ve created HttpRequestMessage extensions to make it easier to use the power of RestClient with DelegatingHandlers.

Take a look at the current DelegatingHandlers that ship with RestClient to give you an idea how easy this is to do.

Before you develop your own handlers see Available Handlers as the functionality you need might already be available

GetContent()

The GetContent() extension method gets the object that was passed in the body of the request, for example restClient.Users.Post(new User{ id = 1 })

Example:

public class MyHandler1 : DelegatingHandler
{
   protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
   {
      var content = request.GetContent();
      request.Content = new StringContent(JsonConvert.SerializeObject(content));   
      
      return await base.SendAsync(request, token); //Call next handler in pipeline
   }
}

GetContent() can return null

ExpectJsonResponse()

The ExpectJsonResponse() extension method either sets or gets whether the RestClient expects json. Setting it to true means that you can take advantage of dynamic response binding.

Example:

public class MyHandler1 : DelegatingHandler
{
   protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
   {
      request.Content = new StringContent("{'foo': 'bar'}");   
      request.ExpectJsonResponse(true);
      return await base.SendAsync(request, token); //Call next handler in pipeline
   }
}

ExpectJsonResponse is set to true by default, but would be false if you called UseNoDefaultHandlers() when creating the RestClient.

GetContentType()

There are various ways the Content-Type header can be set when using RestClient, the GetContentType() extension just ensures you always get the Content-Type header that will be used.

Example:

public class MyHandler1  public class MultipartFormDataHandler : DelegatingHandler
{
   protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   {   
      if (request.GetContentType() != null && request.GetContentType().StartsWith("multipart/form-data"))
      {
         //...
      }
      
	  return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); //next in the pipeline
   }
}

GetContentType() can return null