C# MVC4 project: I want to redirect to a specific page when the session expires.
After some research, I added the following code to the Global.asax
in m
This is some something new in MVC.
Public class SessionAuthorizeAttribute : AuthorizeAttribute
{
Protected override void HandleUnauthorizeRequest(
AuthorizationContext filtercontext )
{
filtercontext.Result = new RedirectResult("~/Login/Index");
}
}
After apply this filter on your controller on those where you want to apply authorization.
[SessionAuthorize]
public class HomeController : Controller
{
// Something awesome here.
}
Above SessionAuthorizeAttribute's HandleUnAuthorizeRequest function will only call once authorization is failed Instead of repeatedly check for authorization.
Regards MK
create this action filter class
class SessionExpireAttribute : ActionFilterAttribute {
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.HttpContext.Session["logged"] == null)
{
filterContext.Result = new RedirectResult("/Account/Login");
}
base.OnActionExecuted(filterContext);
}
then use it in your class or method like bellow
[SessionExpireAttribute]
public class MyController : Controller
{
....
}
The easiest way in MVC is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Index page.
For this purpose you can make a custom attribute as shown :-
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check sessions here
if( HttpContext.Current.Session["username"] == null )
{
filterContext.Result = new RedirectResult("~/Home/Index");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute as shown :
[SessionExpire]
public ActionResult Index()
{
return Index();
}
Or Just add attribute only one time as :
[SessionExpire]
public class HomeController : Controller
{
public ActionResult Index()
{
return Index();
}
}