Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# MVC can you set a global behavior which each action method must carry out before processing the rest of the request?

I've got a rather large MVC web application and I am repeating an action in each controller to see if a customer has completed the application process (in which case a flag is set on their profile which I check against). Ideally I want to remove this code from each action method and have it applied to all action methods which return an action result.

like image 704
BenM Avatar asked Nov 30 '25 09:11

BenM


2 Answers

You could make a custom attribute that handles this for you, you could have the attribute at the Controller level or ActionResult level.

[CompletedApplication("User")]
public ActionResult YourAction
{
    return View();
}

public class CompletedApplicationAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Your logic here
        return true;
    }
}
like image 161
Darren Avatar answered Dec 02 '25 22:12

Darren


If all expected controller inherited from some BaseController than using that, common behavior can be set.

public class HomeController : BaseController
{
}

and BaseContoller will be like

public class BaseController : Controller
{
     protected BaseController(common DI)
     {
     }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
      // some logic after action method get executed      
        base.OnActionExecuted(filterContext);
    }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       // some login before any action method get executed

       string actionName = filterContext.RouteData.Values["action"].ToString(); // Index.en-US

        filterContext.Controller.ViewBag.SomeFlage= true;
    }

  // If Project is in MVC 4 - AsyncContoller support, 
  //below method is called before any action method get called, Action Invoker

   protected override IActionInvoker CreateActionInvoker()
    {       
        return base.CreateActionInvoker();
    }
}
like image 44
111 Avatar answered Dec 02 '25 21:12

111



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!