1st Way:
I used to write a Base Controller class and all other Controllers inherit from it that need to authenticated before access:
public class DefaultController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["User"] == null)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.Result = new JsonResult { Data = "LogOut", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else
filterContext.Result = RedirectToAction("Login", "Account");
}
else
{
//base.Execute(filterContext.RequestContext);
}
}
}
and inherit from Base Controller in the ones for which user must be logged in:
public class LeaveController : DefaultController
{
}
Another way is to write your own authorizaion attribute.
See Filter and Attributes in asp.net mvc
2nd Way:
Here is sample for custom filter attribute, create class which inherits from ActionFilterAttribute
:
public class SessionTimeoutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["someValueYouLookFor"] == null)
{
filterContext.Result = new RedirectResult("~/Home/Index"); // redirect to login action
}
else
{
// continue normal execution
}
}
}
and put it on Controller or Action:
[SessionTimeout]
public ActionResult Index()
{
}