重写modelstate是非常技术性的错误消息
本文关键字:错误 消息 技术性 非常 modelstate 重写 | 更新日期: 2023-09-27 18:01:32
我有以下代码:
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]。"重要性",第一行,第20个位置。我想用一些更友好而不那么暴露的东西来取代这条信息,也许"重要性必须是一个数字。"理想情况下,我希望在DataAnnotation中定义默认转换错误。我尝试使用DataAnnotationsExtensions Nuget在这里http://dataannotationsextensions.org/不幸的是,这针对MVC,并没有覆盖ModelState错误。如果这是不可能覆盖,我很好奇常见的解决方案可能是什么。
一个解决方案(我不太喜欢)是使用对象类型而不是int?类型:
public class Event
{
[DataAnnotationsExtensions.Integer(ErrorMessage = "{0} must be a number.")]
[Range(0,10),Required()]
public object Importance { get; set; }
...
}
如果您这样做,那么转换默认消息将被覆盖。