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

在actionfilterattribute中重复常见错误信息逻辑

  •  3
  • kindohm  · 技术社区  · 16 年前

    我正在使用其余的for ASP.NET MVC框架(MVC 2)实现Web API。我想封装这段代码,最好是在actionfilterattribute(?)中。,以便我可以修饰始终执行相同逻辑的特定操作:

    if (!ModelState.IsValid) {
      return View(
        new GenericResultModel(){ HasError=True, ErrorMessage="Model is invalid."});
    }
    

    我真的不想把这个样板代码复制粘贴到我需要做的每个控制器操作中。

    在这个Web API场景中,我需要能够这样做,以便调用者能够以JSON或POX形式获得结果,并查看是否存在错误。在ASPX视图中,显然我不需要这样的东西,因为验证控件将负责通知用户问题。但是我没有ASPX视图——我只返回从我的模型序列化的JSON或POX数据。

    我已经在ActionFilter中开始使用此代码,但不确定接下来要做什么(或者它是否是正确的起点):

    public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool result = filterContext.Controller.ViewData.ModelState.IsValid;
            if (!result)
            {
                GenericResultModel m = new GenericResultModel() { HasError = true };
                // return View(m)
                // ?????
            }
    
            base.OnActionExecuting(filterContext);
        }     
    

    我怎样才能做到这一点?

    1 回复  |  直到 16 年前
        1
  •  4
  •   Darin Dimitrov    16 年前
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Notice that the controller action hasn't been called yet, so
        // don't expect ModelState.IsValid=false here if you have 
        // ModelState.AddModelError inside your controller action
        // (you shouldn't be doing validation in your controller action anyway)
        bool result = filterContext.Controller.ViewData.ModelState.IsValid;
        if (!result)
        {
            // the model that resulted from model binding is not valid 
            // => prepare a ViewResult using the model to return
            var result = new ViewResult();
            result.ViewData.Model = new GenericResultModel() { HasError = true };
            filterContext.Result = result;
        }
        else
        {
            // call the action method only if the model is valid after binding
            base.OnActionExecuting(filterContext);
        }
    }