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.
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;
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With