在 webapi 项目中,我们有一个类似的模型:
public class Person
{
public string Name { get; set; }
public Guid? Id { get; set; }
}
我们已经配置了参数验证,并使用 ActionFilterAttribute 进行了一些检查:
public class ModelActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
(...)
var modelState = actionContext.ModelState;
if (modelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
base.OnActionExecuting(actionContext);
}
}
问题是,执行如下调用:https://localhost/person?Id=null&name= 'John',会产生如下错误:
The value 'null' is not valid for Id.
我们首先使 Id 字段可以为空,因为我们希望允许像上面那样的调用。尽管如此,验证者还是会抱怨。有什么干净的方法可以排除这个错误吗?
我可以遍历错误列表并排除这个错误,但感觉真的错了。