【发布时间】:2021-06-19 02:06:05
【问题描述】:
Asp.net 核心 3.1 WebApi。
我有一个具有所需属性的模型。
1.如果模型无效,则响应包含数据 喜欢:
{
"errors": {
"Name": [
"Update model can't have all properties as null."
],
"Color": [
"Update model can't have all properties as null."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|f032f1c9-4c36d1e62aa60ead."
}
这对我来说看起来不错。
但是如果我向 modelState.AddModelError("statusId", "Invalid order status id.") 添加一些自定义验证,那么它会返回不同的结构:
[
{
"childNodes": null,
"children": null,
"key": "statusId",
"subKey": {
"buffer": "statusId",
"offset": 0,
"length": 8,
"value": "statusId",
"hasValue": true
},
"isContainerNode": false,
"rawValue": "11202",
"attemptedValue": "11202",
"errors": [
{
"exception": null,
"errorMessage": "Invalid order status id."
}
],
"validationState": 1
}
]
看起来 ModelState.IsValid 实际上不再适用于控制器,因为错误的请求甚至在进入无效模式的控制器之前就返回了。还是有一些通过 ModelSate 进行全局验证的标志?
为什么结构不同? 如何让它一样? 如何在 MVC 中强制访问 api 控制器内部的 ModelState.IsValid 方法?
更新:
[Route("....")]
[Authorize]
[ApiController]
public class StatusesController : ApiControllerBase
{
[HttpPut, Route("{statusId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
[Produces("application/json")]
public async Task<ObjectResult> UpdateStatusAsync(int statusId, [FromBody] StatusUpdateDto orderStatusUpdateDto)
{
int companyId = User.Identity.GetClaimValue<int>(ClaimTypes.CompanyId);
const string errorNotFound = "There is not order status with this id for such company";
if (statusId <= 0)
{
Logger.LogError(errorNotFound);
ModelState.AddErrorModel(nameof(statusId), "Invalid order status id")
throw new NotFound(ModelState);
}
if (orderStatusUpdateDto == null)
{
const string error = "Invalid (null) order status can't be added";
Logger.LogError(error);
throw new ArgumentNullException(error);
}
if (ModelState.IsValid == false) // also this code is always true or returns 400 before this line
{
return BadRequest(ModelState);
}
....
return result;
}
}
【问题讨论】:
-
您在哪里将错误添加到模型状态?在控制器方法里面?你用 ApiController 属性装饰控制器吗?
-
在控制器方法内部 - 是的,用 ApiController 装饰控制器 - 是的
-
除了下面treze的回答外,您还可以使用
.ConfigureApiBehaviorOptions(o => o.InvalidModelStateResponseFactory = ...)配置用于产生无效模型结果的工厂。
标签: asp.net-mvc validation asp.net-core asp.net-web-api modelstate