Where can you find model binding errors in ASP.NET Core MVC?

非 Y 不嫁゛ 提交于 2019-12-19 09:27:22

问题


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

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)?


回答1:


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: 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) ...

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

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

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

|improve this answer

来源:https://stackoverflow.com/questions/49244454/where-can-you-find-model-binding-errors-in-asp-net-core-mvc

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