1

在 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 字段可以为空,因为我们希望允许像上面那样的调用。尽管如此,验证者还是会抱怨。有什么干净的方法可以排除这个错误吗?

我可以遍历错误列表并排除这个错误,但感觉真的错了。

4

1 回答 1

0

您可以定义特定于目的的模型。例如:

public class PersonSearchParameters
{
    public string Name { get; set; }

    public string Id { get; set; }
}

然后让您的方法以Id您喜欢的方式处理解析。

不过,我真的认为这会更容易,如果你只是说id如果你希望它为空,应该从你的结果中省略它。

于 2017-08-03T21:04:22.203 回答