ASP.NET Core handling JSON deserialization problems

与世无争的帅哥 提交于 2021-01-28 05:15:21

问题


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

  1. 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;
            };
        }
    }
    
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!