0

Is it possible to tell Refit not to try and serialise the message body for certain HttpStatus Codes?

I'm integrating with an API that (when authentication fails) returns a HTML body instead of JSON alongside a 203 status code instead of a 401/403 status code. This means Refit will attempt to serialise the body and throw a SerializationException instead of an ApiException.

Is it possible to handle this instance? I.e. tell Refit to only treat 200 as successful or inject a step in prior to deserialization that has access to the status code?

Jamie Peacock
  • 372
  • 4
  • 15

1 Answers1

3

You can use a DelegatingHandler.

public class JamiesHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
       var response = await base.SendAsync(request, cancellationToken);

       // Do stuff with the response here...

       return response;
    }
}

// Then
var httpClient = new HttpClient(new JamiesHandler()){ BaseAddress = ""};
var contract = Refit.RestService.For<SomeContract>(httpClient);

Here is an example of this being done with Refit for logging.

Drewness
  • 5,004
  • 4
  • 32
  • 50
  • I thought I'd have to go down a route like this, and then throw some kind of custom exception (or fake a response and pop that in the ApiException) in the case it goes wrong! Thanks a lot :) – Jamie Peacock Mar 30 '19 at 08:38