覆盖ModelState的技术性错误消息

时间:2015-07-07 20:27:42

标签: c# asp.net asp.net-web-api2 model-binding modelstate

我有以下代码:

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."
]

}     }

我担心&#34;无法将字符串转换为整数:1.1。路径&#39; [0]。重要性&#39;,第1行,第20位。&#34; 我想用更友好,更少揭示的东西来覆盖这个消息,也许&#34;重要性必须是一个数字。&#34;。理想情况下,我想在DataAnnotation中定义默认转换错误。我尝试使用此处找到的DataAnnotationsExtensions Nuget http://dataannotationsextensions.org/,遗憾的是,这是针对MVC并且不会覆盖ModelState错误。如果无法覆盖,我很好奇常见的解决方法可能是什么。

1 个答案:

答案 0 :(得分:2)

一个解决方案(我不太喜欢)将使用对象类型而不是int?类型:

public class Event
{
    [DataAnnotationsExtensions.Integer(ErrorMessage = "{0} must be a number.")]
    [Range(0,10),Required()]        
    public object Importance { get; set; }

    ...
}

如果您这样做,那么将覆盖转换默认消息。