我有这个简单的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.Serialize
和Int64StringConversionFormatter.Deserializ
方法永远不会被调用。我使用另一种简单的格式化程序(例如UnixDateTimeFormatter
)测试了配置,并且工作正常。但是我无法弄清楚为什么这个人没有得到称呼。你知道我在这里想念什么吗?