问题描述
对于我特定的.NET Core 2.1应用程序,我已经确定System.Text.Json的性能要比Newtonsoft好得多。我知道这是.NET Core 3.x的默认设置,但是我还不能升级到该版本。
在单个端点中,我可以使用System.Text.Json进行序列化
System.Text.Json.JsonSerializer.Serialize(data,options);
但是我不清楚如何将其作为整个应用程序的默认设置。如果要在Startup.cs
中调整Jsonoptions,则SerializerSettings
对象是Newtonsoft的一部分。
.AddJsonoptions(options =>
{
options.SerializerSettings...
});
是否可以更改.NET Core 2.1应用程序的默认Json序列化程序?
解决方法
您似乎可以尝试使用输入/输出格式化程序的自定义实现。
有一个使用protobuf处理序列化的示例。 https://dejanstojanovic.net/aspnet/2018/september/custom-input-and-output-serializers-in-aspnet-core/
我认为您对在此处查看MSDN官方文档最感兴趣:
https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/custom-formatters?view=aspnetcore-2.1
public class JsonInputFormatter : TextInputFormatter,IInputFormatterExceptionPolicy
{
public InputFormatterExceptionPolicy ExceptionPolicy { get; }
public JsonInputFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context,Encoding encoding)
{
string request = null;
using(var sr = new StreamReader(context.HttpContext.Request.Body))
{
request = await sr.ReadToEndAsync();
}
var result = JsonSerializer.Deserialize(request,context.ModelType);
return await InputFormatterResult.SuccessAsync(result);
}
}