[英]ASP.NET Core handling JSON deserialization problems
我想更改 ASP.NET 核心中无效 JSON 请求处理的默认行为。 我有这个 model:
public class Model
{
public Guid Id { get; set; }
}
当我用这个身体发送这个请求时
{
"Id": null
}
它返回此错误消息:
"Error converting value {null} to type 'System.Guid'. Path 'Id', line 2, position 11."
当然这绝对合乎逻辑,但我希望将 Id 设置为默认值 (Guid.Empty) 而不是失败的请求。 我在启动中添加了这个 json 配置:
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.Error = (a, e) =>
{
e.ErrorContext.Handled = true;
})
错误处理程序被命中,但是 ASP.NET 核心仍然返回失败。 与 ASP.NET Web API 相比,这在不同的行为中是可能的。
如您所见,此行为由 JsonInputFormatter 处理,您可以自定义格式化程序以覆盖此行为,例如
IgnoreGuidErrorJsonInputFormatter
public class IgnoreGuidErrorJsonInputFormatter: JsonInputFormatter { public IgnoreGuidErrorJsonInputFormatter(ILogger logger, JsonSerializerSettings serializerSettings, ArrayPool<char> charPool, ObjectPoolProvider objectPoolProvider, MvcOptions options, MvcJsonOptions jsonOptions): base(logger, serializerSettings, charPool, objectPoolProvider, options, jsonOptions) { serializerSettings.Error = (a, e) => { var errors = e.ErrorContext.Error; e.ErrorContext.Handled = true; }; } }
注册IgnoreGuidErrorJsonInputFormatter
services.AddMvc(options => { var serviceProvider = services.BuildServiceProvider(); var customJsonInputFormatter = new IgnoreGuidErrorJsonInputFormatter( serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger<IgnoreGuidErrorJsonInputFormatter>(), serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value.SerializerSettings, serviceProvider.GetRequiredService<ArrayPool<char>>(), serviceProvider.GetRequiredService<ObjectPoolProvider>(), options, serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value ); options.InputFormatters.Insert(0, customJsonInputFormatter); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.