Repeat common error logic logic in ActionFilterAttribute

I am using the web API using REST for the ASP.NET MVC framework (MVC 2). I want to encapsulate this code, ideally, in ActionFilterAttribute (?), So that I can decorate specific actions that always follow the same logic:

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

I really don't want to copy and paste this boilerplate code into every controller action where I need to do this.

In this web API scenario, I need to do something similar so that the caller can get the result in the form of JSON or POX and see that there is an error. In the ASPX view, obviously, I will not need something like this, since the validation controls will take care to notify the user about the problem. But I don't have an ASPX view - I only return JSON or POX data serialized from my model.

I started with this code in ActionFilter, but I'm not sure what to do next (or even if this is the right starting point):

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);
    }     

How to do it?

+3
source share
1 answer
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);
    }
}
+4
source

Source: https://habr.com/ru/post/1751467/


All Articles