ASP.NET Core处理JSON反序列化问题 [英] ASP.NET Core handling JSON deserialization problems

查看:177
本文介绍了ASP.NET Core处理JSON反序列化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改ASP.NET Core中无效JSON请求处理的默认行为.我有这个模型:

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
}

它返回此错误消息:

 "Error converting value {null} to type 'System.Guid'. Path 'Id', line 2, position 11."

当然,这绝对是合乎逻辑的,但我希望将ID设置为默认值(Guid.Empty),而不是失败的请求.我在启动中添加了这个json配置:

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;
            })

错误处理程序被命中,但是ASP.NET Core仍然返回失败.与可能的ASP.NET Web API相比,这具有不同的行为.

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.

推荐答案

如您所见,此行为由JsonInputFormatter处理,您可以自定义格式化程序以覆盖此行为,如

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;
        };
    }
}

  • 注册 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);
    });
    

  • 这篇关于ASP.NET Core处理JSON反序列化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆