System.Text.Json in Refit can't handle null response from API

Viewed 527

Suppose I have a Refit interface:

public interface SomeApi
{
    [Get("/DoStuff")]
    Task<MyClass> DoStuff();
} 

I register this refit client in my dependency injection with System.Text.Json:

services.AddRefitClient<SomeApi>(new RefitSettings(
                                    new SystemTextJsonContentSerializer(
                                        new JsonSerializerOptions
                                            {
                                                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                                            })))
        .ConfigureHttpClient(ConfigureClient(config));

This code used to use Newtonsoft.Json, and has been refactored to use System.Text.Json. However,my /DoStuff endpoint can return null. With System.Text.Json, this will throw an exception in my Refit client. With Newtonsoft this works fine.

How do I get the above code to work if my api endpoints can return null?

1 Answers
new JsonSerializerOptions
    {
       PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
       DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
    }

documentation

Related