Reputation: 1620
Is there any way to execute a method in a controller before any action is called automatically? For example, let's say I have the login credentials of the user stored in cookies, I have a user controller and any time any of the actions in that controller is called I wanna check if the user is logged in or not. (instead of calling that method in each action individually)
public ActionResult Test () {
if (Checklogin()) {
return View();
}
else {
return new EmptyView();
}
}
I wanna make all the methods follow this logic but without defining this in each one of them individually.
Upvotes: 2
Views: 2223
Reputation: 5755
As suggested in the comments use the ActionFilter. If your conditions are not met, like if the cookie is expired or something, call the action made for displaying the error message in the overridden method.
public class AuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (Condition Not Met)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Error Message Controller",
action = "Error Message Action"
}));
}
}
}
Upvotes: 3