0

I need to use different Json.NET's JSON Converters depends on header. Some think like this:

services
    .AddMvcCore()                
    .AddJsonOptions(options =>
    {
        // If(my_custom_header_value =="use_first_converter")
        options.SerializerSettings.Converters.Add(new FirstConverter());
        // Else
        //options.SerializerSettings.Converters.Add(new FirstConverter());
    })
0

For converting depending on custom requests' header, it is impossible to setup by AddJsonOptions. You could not access the HttpContext during ConfigureServices since there is no request during this process.

For a workaround, try register IHttpContextAccessor like

public class FirstConverter : JsonConverter
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public FirstConverter(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    public override bool CanConvert(Type objectType)
    {
        var header = _httpContextAccessor.HttpContext.Request.Headers;
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

And then in ConfigureServices

services.AddMvc().AddJsonOptions(options =>
{
    var httpContextAccessor = services.BuildServiceProvider().GetRequiredService<IHttpContextAccessor>();
    // If(my_custom_header_value =="use_first_converter")
    options.SerializerSettings.Converters.Add(new FirstConverter(httpContextAccessor));
    // Else
    //options.SerializerSettings.Converters.Add(new FirstConverter());
});

Check wether to convert by var header = _httpContextAccessor.HttpContext.Request.Headers;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.