如何根据自定义请求的标头设置Json.NET的Converters

时间:2019-04-15 23:32:06

标签: asp.net-core json.net

我需要根据标题使用不同的Json.NET的JSON转换器。 有人这样想:

fullpath = '/path/to/some/file.jpg'
index = fullpath.rfind('/')
fullpath[0:index]

1 个答案:

答案 0 :(得分:0)

要根据自定义请求的标头进行转换,无法通过AddJsonOptions进行设置。您无法在ConfigureServices期间访问HttpContext,因为在此过程中没有请求。

要解决此问题,请尝试像

那样注册IHttpContextAccessor
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();
    }
}

然后在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());
});

检查是否可以通过var header = _httpContextAccessor.HttpContext.Request.Headers;进行转换