您在哪里可以找到ASP.NET Core MVC中的模型绑定错误? [英] Where can you find model binding errors in ASP.NET Core MVC?

查看:83
本文介绍了您在哪里可以找到ASP.NET Core MVC中的模型绑定错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对对象执行模型绑定时,如果对象的任何属性的类型不匹配,框架似乎都将返回null.例如,请考虑以下简单示例:

When performing model binding to objects, it seems that the framework will return null if there are type mismatches for any of the object's properties. For instance, consider this simple example:

public class Client
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime RegistrationDate { get; set; }
}

public class ClientController : Controller
{
    [HttpPatch]
    public IActionResult Patch([FromBody]Client client)
    {
        return Ok("Success!");
    }
}

如果我在HTTP请求中为Age属性提交了一个"asdf"值,那么无论其他属性如何提交,整个Patch方法中的client参数都将为null. RegistrationDate属性也是如此.因此,当控制器操作中FromBody参数为null时,如何知道导致模型绑定失败的错误(在这种情况下,哪个提交的属性具有错误的类型)?

If I submit a value of "asdf" for the Age property in an HTTP request, the entire client parameter will be null in the Patch method, regardless of what's been submitted for the other properties. Same thing for the RegistrationDate property. So when your FromBody argument is null in your controller action, how can you know what errors caused model binding to fail (in this case, which submitted property had the wrong type)?

推荐答案

如您所述,ASP.NET MVC内核已更改了MVC API默认情况下处理模型绑定的方式.您可以使用当前的ModelState查看哪些项目失败以及由于什么原因.

As you stated, ASP.NET MVC core has changed the way MVC API handles model binding by default. You can use the current ModelState to see which items failed and for what reason.

   [HttpPatch]
    [Route("Test")]
    public IActionResult PostFakeObject([FromBody]Test test)
    {
        foreach (var modelState in ViewData.ModelState.Values)
        {
            foreach (var error in modelState.Errors)
            {
              //Error details listed in var error
            }
        }
        return null;
    }
}

错误消息中存储的异常状态如下:

The exception stored within the error message will state something like the following:

Exception = {Newtonsoft.Json.JsonReaderException:无法转换 字符串到整数:饼图.路径年龄",第1行,位置28.在 Newtonsoft.Json.JsonReader.ReadInt32String(String s)在 Newtonsoft.Json.JsonTextReader.FinishReadQuotedNumber(ReadType readType)...

Exception = {Newtonsoft.Json.JsonReaderException: Could not convert string to integer: pie. Path 'age', line 1, position 28. at Newtonsoft.Json.JsonReader.ReadInt32String(String s) at Newtonsoft.Json.JsonTextReader.FinishReadQuotedNumber(ReadType readType) ...

但是,如上面评论中所述,Microsoft文档解释了以下内容:

However, as posted in the comments above, the Microsoft docs explains the following:

如果绑定失败,则MVC不会引发错误.每一个动作 接受用户输入时,应检查ModelState.IsValid属性.

If binding fails, MVC doesn't throw an error. Every action which accepts user input should check the ModelState.IsValid property.

注意:控制器的ModelState属性中的每个条目都是一个 包含Errors属性的ModelStateEntry.几乎没有必要 自己查询该集合.请改用ModelState.IsValid. https://docs.microsoft.com/zh-我们/aspnet/core/mvc/models/model-binding

Note: Each entry in the controller's ModelState property is a ModelStateEntry containing an Errors property. It's rarely necessary to query this collection yourself. Use ModelState.IsValid instead. https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

这篇关于您在哪里可以找到ASP.NET Core MVC中的模型绑定错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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