Redirect to specific page after session expires (M

2019-01-14 03:18发布

问题:

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 my project:

protected void Session_End(object sender, EventArgs e)
{
     Response.Redirect("Home/Index");
}

When the session expires, it throws an exception at the line Response.Redirect("Home/Index"); saying The response is not available in this context

What's wrong here?

回答1:

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


回答2:

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