流畅的验证:如何自定义错误的请求消息格式?

时间:2016-08-02 09:32:35

标签: c# asp.net asp.net-web-api fluentvalidation

在我的控制器中,我已经检查了一下:

if (!ModelState.IsValid)
{
   return BadRequest(ModelState);
}

这给了我错误的具体格式,例如:

{
  "Message": "The request is invalid.",
  "ModelState": {
    "stocks.SellerType": [
      "SellerType should be greater than 101"
    ],
    "stocks.SourceId": [
      "SourceId should be less than 300"
    ]
  }
}

如何自定义此错误消息格式。我知道如何自定义错误消息,即“SourceId应小于300”。但我不知道如何更改“消息”,删除或重命名json字段“ModelState”?

1 个答案:

答案 0 :(得分:1)

更新:更改默认消息并保留ModelState错误的默认格式HttpError类:

if (!ModelState.IsValid)
{
    return Content(HttpStatusCode.BadRequest,
        new HttpError(ModelState, includeErrorDetail: true)
        {
            Message = "Custom mesage"
        });
}

或者您可以为验证结果定义自己的模型,并使用所需的状态代码返回它(重命名json字段" ModelState")。例如:

class ValdationResult
{
    public string Message { get; }
    public HttpError Errors { get; }

    public ValdationResult(string message, ModelStateDictionary modelState)
    {
        Message = message;
        Errors = new HttpError(modelState, includeErrorDetail: true).ModelState;
    }
}
...

if (!ModelState.IsValid)
{
    return Content(HttpStatusCode.BadRequest, 
        new ValdationResult("Custom mesage", ModelState));
}
相关问题