首页 文章

如何在ASP.NET Core MVC中处理模型绑定异常?

提问于
浏览
0

从模板创建一个简单的ASP.NET Core MVC Web应用程序 . 创建一个名为 Human 的类:

public class Human
{
    public string Name { get; set; }

    public int Age { get; set; }

    public DateTime Birthday { get; set; }
}

现在创建 HumanController 以发布人工实例:

[HttpPost]
public Human Post([FromBody] Human human)
{
    return human;
}

使用Fiddler或PostSharp(或任何其他客户端)将这些JSON对象发布到此服务:

{
    "Name": "someone"
}

{
    "Name": "someone",
    "Age": "invalid age"
}

{
    "Name": "someone",
    "Birthday": null
}

由于 Birthday 不能为null且 "invalid age" 无法解析为有效的模型属性,因此我们在service参数中获得的内容为null . 事实证明这很难调试 .

有没有办法我们可以将ASP.NET Core MVC配置为尽可能多地部分绑定模型,或以某种方式让我们挂钩其默认行为,以便我们可以捕获异常并通知客户端它有错误的数据发送?

1 回答

  • 2

    我认为如果您将正确的属性添加到模型中,您可以将其添加到客户端并将正确的错误消息返回给客户端 . 例如,您可以在 Name 上添加一些需求:

    public class Human
    {
        [Required(ErrorMessage ="")]
        [StringLength(10)]
        public string Name { get; set; }
    
        public int Age { get; set; }
    
        public DateTime Birthday { get; set; }
    }
    

    通过这种方式,您可以检查您的模型,如果它无效,请返回 BadRequest ,如:

    public IActionResult Index(Human model)
        {
            if (!ModelState.IsValid)
                return BadRequest("message");
            //to do
            return View();
        }
    

相关问题