问题
I would like to change default behavior of invalid JSON request handling in ASP.NET Core. I have this model:
public class Model
{
public Guid Id { get; set; }
}
And when I send this request with this body
{
"Id": null
}
It returns this error message:
"Error converting value {null} to type 'System.Guid'. Path 'Id', line 2, position 11."
Of course this is absolutely logical but I want Id to be set to default value (Guid.Empty) instead of failing request. I have added this json config in Startup:
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.Error = (a, e) =>
{
e.ErrorContext.Handled = true;
})
Error handler is being hit however ASP.NET Core still returns failure. This in different behavior compared to ASP.NET Web API where this was possible.
回答1:
As you have found, this behavior is handled by JsonInputFormatter, you could custom the formatter to override this behavior like
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; }; } }
Register
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); });
来源:https://stackoverflow.com/questions/58018207/asp-net-core-handling-json-deserialization-problems