Utf8Json中的自定义JsonFormatter被忽略

时间:2020-02-09 12:12:44

标签: c# .net-core asp.net-core-3.1 .net-core-3.1 utf8json

我有这个简单的JsonFormatter:

public sealed class Int64StringConversionFormatter : IJsonFormatter<long> {

    public void Serialize(ref JsonWriter writer, long value, IJsonFormatterResolver formatterResolver) {
        writer.WriteString(value.ToString(NumberFormatInfo.InvariantInfo));
    }

    public long Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) {
        var token = reader.GetCurrentJsonToken();

        if (token == JsonToken.String) {
            var s = reader.ReadString();
            return
                long.TryParse(s, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var l)
                    ? l
                    : 0;
        }

        if (token != JsonToken.Number)
            throw new ValueProviderException("The provided value is not String or Int64.");

        var value = reader.ReadInt64();

        return value;

    }

}

这是Utf8Json.IJsonFormatter<>的实现,用于处理long值。我已经将这种格式化程序添加到这样的AspNetCore WebApi应用程序中:

public static MvcOptions SetupCustomJsonFormatter(
    this MvcOptions options) {
    CompositeResolver.RegisterAndSetAsDefault(_formatters, _resolvers);

    options.InputFormatters.Insert(0, new Utf8JsonInputFormatter());
    options.OutputFormatters.Insert(0, new Utf8JsonOutputFormatter());

    return options;
}

这是我的_formatters_resolvers

static readonly IJsonFormatterResolver[] resolvers = {
    StandardResolver.ExcludeNullCamelCase, 
    ImmutableCollectionResolver.Instance,
    EnumResolver.Default, 
    DynamicGenericResolver.Instance, 
};

static readonly IJsonFormatter[] _formatters 
    = new [] {new Int64StringConversionFormatter()};

此外,这是我的Utf8JsonInputFormatter

internal sealed class Utf8JsonInputFormatter : IInputFormatter {

    private readonly IJsonFormatterResolver _resolver;

    public Utf8JsonInputFormatter() : this(null) {
    }

    public Utf8JsonInputFormatter(IJsonFormatterResolver resolver) {
        _resolver = resolver ?? JsonSerializer.DefaultResolver;
    }

    public bool CanRead(InputFormatterContext context)
        => context.HttpContext.Request.ContentType?.StartsWith("application/json") == true;

    public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context) {
        var request = context.HttpContext.Request;

        if (request.Body.CanSeek && request.Body.Length == 0) return await InputFormatterResult.NoValueAsync();

        var result = await JsonSerializer.NonGeneric.DeserializeAsync(context.ModelType, request.Body, _resolver);

        return await InputFormatterResult.SuccessAsync(result);
    }

}

一切似乎都应该没问题。但是Int64StringConversionFormatter.SerializeInt64StringConversionFormatter.Deserializ方法永远不会被调用。我使用另一种简单的格式化程序(例如UnixDateTimeFormatter)测试了配置,并且工作正常。但是我无法弄清楚为什么这个人没有得到称呼。你知道我在这里想念什么吗?

0 个答案:

没有答案