Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - Redirect to specific page after session expires (MVC4)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...