【发布时间】:2020-01-25 11:05:36
【问题描述】:
我有一个带有 ActionFilter 的 ASP NET Core 2.1 API(自动 ModelState 验证被抑制),并且当出现绑定错误时 - 例如要绑定到 guid 的无效字符串 - 模型状态仅包含来自绑定的错误,但不包含其他错误 - 需要属性或 MaxLength 等。这是预期的吗?还有更重要的问题:有没有办法在一次旅行中获取所有模型状态错误?
我的操作过滤器(全局):
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
绑定模型:
public class SkillBindDto
{
[Required(ErrorMessage = ValidationMessages.FieldRequired)]
[MinLength(1, ErrorMessage = ValidationMessages.FieldInvalidMinLength)]
public string Name { get; set; }
public string Info { get; set; }
[Required(ErrorMessage = ValidationMessages.FieldRequired)]
public Guid SectionId { get; set; }
public string[] Tags { get; set; }
}
控制器中的Action方法
[HttpPost()]
public async Task<ActionResult<IReadOnlyCollection<SkillDto>>> Create([FromBody]ICollection<SkillBindDto> skills, CancellationToken cancellationToken)
{
List<SkillDto> result = await _skillService.CreateSkillsAsync(skills, cancellationToken);
return result;
}
还有两个例子: 当请求的正文是:
[
{
SectionId : "0c2d3928-aff2-44da-blaaah-blaaah", - this is invalid guid
Name : "",
Info : "Test Info",
Tags : ["tag 1", "tag 2"]
},
{
SectionId : "0c2d3928-aff2-44da-blaaah-blaaah", - this is invalid guid
Name : "",
Info : "Test Info 2",
Tags : ["tag 3", "tag 2"]
}
]
我收到了这样的回复:
{
"[0].SectionId": [
"Error converting value \"0c2d3928-aff2-44da-blaaah-blaaah\" to type 'System.Guid'. Path '[0].SectionId', line 3, position 51."
],
"[1].SectionId": [
"Error converting value \"0c2d3928-aff2-44da-blaaah-blaaah\" to type 'System.Guid'. Path '[1].SectionId', line 9, position 51."
]
}
当 Section Id guid 有效时:
[
{
SectionId : "0c2d3928-aff2-44da-5d98-08d727c1a8b0",
Name : "",
Info : "Test Info",
Tags : ["tag 1", "tag 2"]
},
{
SectionId : "0c2d3928-aff2-44da-5d98-08d727c1a8b0",
Name : "",
Info : "Test Info",
Tags : ["tag 3", "tag 2"]
}
]
结果是:
{
"[0].Name": [
"Field Name is not provided but it is required",
"Field Name is under minimum length. Lenght must be not less than 1 character(s)"
],
"[1].Name": [
"Field Name is not provided but it is required",
"Field Name is under minimum length. Lenght must be not less than 1 character(s)"
]
}
【问题讨论】:
标签: c# asp.net-core