Search code examples
c#.net-corerefit

Is it possible to configure when Refit should attempt deserialization?


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?


Solution

  • 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.