代码之家  ›  专栏  ›  技术社区  ›  Cyan

排除ActionFilterAttribute中的“值“null”对…无效”

  •  1
  • Cyan  · 技术社区  · 8 年前

    在webapi项目中,我们有这样一个模型:

    public class Person
    {
        public string Name { get; set; }
    
        public Guid? Id { get; set; }
    }
    

    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.
    

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

    1 回复  |  直到 8 年前
        1
  •  0
  •   StriplingWarrior    8 年前

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

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

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

    我真的认为如果你这么说的话会更容易 id 如果希望它为null,则应该从结果中省略。

    推荐文章