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.
Asked
Active
Viewed 414 times
2 Answers
5
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;
}
}

Darren
- 68,902
- 24
- 138
- 144
-
For the OPs scenario this would work better since it can be better controlled, rather than a BaseController or ActionFilters which would be hard to target *only* methods which return an action result – Jun Wei Lee Oct 02 '13 at 00:02
3
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();
}
}

111
- 1,779
- 1
- 12
- 15