【发布时间】:2023-08-03 07:53:01
【问题描述】:
我有以下代码:
public class EventController : ApiController
{
public IHttpActionResult Post(List<Event> Events)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
else
{
foreach (Event Event in Events)
{
Debug.WriteLine(Event.Importance.ToString());
Debug.WriteLine(Event.Date.ToString());
Debug.WriteLine(Event.Description);
}
return Ok();
}
}
}
public class Event
{
[DataAnnotationsExtensions.Integer(ErrorMessage = "{0} must be a number.")]
[Range(0,10),Required()]
public int? Importance { get; set; }
public DateTime Date { get; set; }
[RegularExpression(@"^.{20,100}$", ErrorMessage="{0} must be between 20 and 100 characters.")]
public string Description { get; set; }
}
我正在发布以下 JSON:
[{"Importance":"1.1","Date":"2015-03-12","Description":""},{"Importance":"6","Date":"2015-10-02","Description":"a"}]
回复是:
{
"Message": "The request is invalid.",
"ModelState": {
"Events[0].Importance": [
"Could not convert string to integer: 1.1. Path '[0].Importance', line 1, position 20.",
"The Importance field is required."
],
"Events[1].Description": [
"Description must be between 20 and 100 characters."
]
} }
我担心“无法将字符串转换为整数:1.1。路径 '[0].Importance',第 1 行,位置 20。” 我想用更友好、不那么暴露的东西来覆盖这条信息,也许是“重要性必须是一个数字。”。理想情况下,我想在 DataAnnotation 中定义默认转换错误。我尝试使用在这里找到的 DataAnnotationsExtensions Nuget http://dataannotationsextensions.org/ 不幸的是,这针对 MVC 并且不会覆盖 ModelState 错误。如果这无法覆盖,我很好奇常见的解决方法可能是什么。
【问题讨论】:
标签: c# asp.net asp.net-web-api2 model-binding modelstate