在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字段设为可空,因为我们希望允许上面的调用。验船师还在抱怨。有没有干净的方法来排除这个错误?
我可以去遍历错误列表并排除这个错误,但感觉真的错了。
答案 0 :(得分:0)
您可以定义特定于目的的模型。例如:
public class PersonSearchParameters
{
public string Name { get; set; }
public string Id { get; set; }
}
然后让您的方法以您希望的方式处理解析Id
。
我真的认为,如果你只是说如果你想让它为空,那么你的结果中应该省略id
会更容易。