问题说明了一切,我有一个Web API控制器动作,需要一个POCO。这是一个POST动作,我故意不将参数发布到动作,但是ModelState.IsValid属性仍然显示为true。那为什么会这样?是否有一个属性我必须在控制器操作及其参数上设置以强制执行验证?
答案 0 :(得分:1)
Null是对象的有效值。使POCO [必需]中的属性强制执行检查。
答案 1 :(得分:0)
有类似的问题。你有一个有效的担忧。请看一下:
https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/
数据 - 拯救的注释:
public class ValidateActionParametersAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
var parameters = descriptor.MethodInfo.GetParameters();
foreach (var parameter in parameters)
{
var argument = context.ActionArguments[parameter.Name];
EvaluateValidationAttributes(parameter, argument, context.ModelState);
}
}
base.OnActionExecuting(context);
}
private void EvaluateValidationAttributes(ParameterInfo parameter, object argument, ModelStateDictionary modelState)
{
var validationAttributes = parameter.CustomAttributes;
foreach (var attributeData in validationAttributes)
{
var attributeInstance = CustomAttributeExtensions.GetCustomAttribute(parameter, attributeData.AttributeType);
var validationAttribute = attributeInstance as ValidationAttribute;
if (validationAttribute != null)
{
var isValid = validationAttribute.IsValid(argument);
if (!isValid)
{
modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name));
}
}
}
}
}
然后使用它:
[ValidateActionParameters]
public IActionResult Post([FromBody][Required]Product product)