Redirect to specific page after session expires (MVC4)

人盡茶涼 提交于 2019-11-27 19:51:17

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();
  }
}

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
{
    ....
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!