Fluent validation:如何自定义错误的请求消息格式?
Fluent validation: How to customize the bad request message format?
在我的控制器中,我进行了检查:
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 should be less than 300"。但我不知道如何更改 "Message"、删除或重命名 json 字段 "ModelState"?
更新:要更改默认消息并保持 ModelState
错误的默认格式,您可以使用 HttpError
class:
if (!ModelState.IsValid)
{
return Content(HttpStatusCode.BadRequest,
new HttpError(ModelState, includeErrorDetail: true)
{
Message = "Custom mesage"
});
}
或者您可以为验证结果定义自己的模型,并 return 它具有所需的状态代码(重命名 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));
}
在我的控制器中,我进行了检查:
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 should be less than 300"。但我不知道如何更改 "Message"、删除或重命名 json 字段 "ModelState"?
更新:要更改默认消息并保持 ModelState
错误的默认格式,您可以使用 HttpError
class:
if (!ModelState.IsValid)
{
return Content(HttpStatusCode.BadRequest,
new HttpError(ModelState, includeErrorDetail: true)
{
Message = "Custom mesage"
});
}
或者您可以为验证结果定义自己的模型,并 return 它具有所需的状态代码(重命名 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));
}