json 如何使ASP.NET核心部分绑定到有效数据?

hkmswyz6  于 2022-12-05  发布在  .NET
关注(0)|答案(2)|浏览(156)

假设我有这样一个模型:

public enum State
{
    Valid = 1,
    Invalid = 2
}

public class Person
{
    public string Name { get; set; }
    
    public State state { get; set; }
}

而这个控制器动作:

[HttpPost]
public object SavePerson([FromBody] Person person)
{
    return person;
}

如果我发送这个JSON,一切都正常:

{
    "name": "John",
    "state": 1
}

但是,如果我将"state": 1更改为无效枚举,如"state": """state": "1",则person参数将为空。
换句话说,如果我发送一个部分有效的JSON,ASP.NETCore将忽略所有字段。
如何配置ASP.NETCore以至少从正文中提取有效字段?

06odsfpq

06odsfpq1#

您需要处理反序列化异常。
每次在字段中遇到问题时,此代码都会放置一个默认值,但json字符串本身必须是有效的json字符串。

static void Main(string[] args)
    {
        //This should be run on startup code (there are other ways to do that as well - you can put this settings only on controllers etc...)
        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Error = HandleDeserializationError
        };

        var jsonStr = "{\"name\": \"John\",\"state\": \"\" }";
        var person = JsonConvert.DeserializeObject<Person>(jsonStr);         

        Console.WriteLine(JsonConvert.SerializeObject(person)); //{"Name":"John","state":0}
    }

    public static void HandleDeserializationError(object sender, ErrorEventArgs args)
    {
        var error = args.ErrorContext.Error.Message;
        args.ErrorContext.Handled = true;
    }

对于WebAPI,您应该有一个Startup.cs文件,如下所示:

public void ConfigureServices(IServiceCollection services)
    {
        //look for services.AddControllers() -> or add it if it does not exist
        services.AddControllers()
            .AddMvcOptions(options =>
            {
               //... might have options here
            })
               //this is what you need to add
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.Error = HandleDeserializationError
            });
    }
zz2j4svz

zz2j4svz2#

请尝试以下可为空的运算符:

public State? state { get; set; }

相关问题