会话超时后重定向到登录页面

时间:2016-12-30 10:10:40

标签: c# asp.net-mvc session session-timeout

首先,我已经看过以下类似的解决方案:

ASP.NET MVC : Handle Session Expire Using Custom Attribute

Redirect to specific page after session expires (MVC4)

但是我需要一个关于这个问题的智能解决方案,只需在Global.asax等上键入代码,而不需要在每个Cntroller上额外实现。可能吗?如果没有,在ASP.NET MVC会话超时后重定向到登录页面的最佳方法是什么?

4 个答案:

答案 0 :(得分:0)

您可以使用Global.asax方法在Session_End处理会话超时。 仅供参考,它有一些缺点:它不会在超时后被调用,如果你的会话在运行时内存中,它就可以工作。尝试一下,也许这对你的情况来说已经足够了。

另一种方法是使用SessionStateModule或创建自定义HTTP moduleglobal events配对,可用于会话控制。

答案 1 :(得分:0)

使用新设置的MVC应用程序对此进行测试。它背后的想法,即检查每个传入请求的会话状态似乎在我的情况下正常工作。

void Application_PostAcquireRequestState(object sender, EventArgs e)
{
    HttpContext context = ((HttpApplication)sender).Context;
    if (context.Session != null)
    {
        if (context.Session["sessionExist"] is bool && (bool)context.Session["sessionExist"])
            return;
    }

    // put code here that you want to execute if the session has expired
    // for example:

    FormsAuthentication.SignOut();

    // or maybe

    context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
}

然后在用户成功登录后添加Session["sessionExist"] = true;

答案 2 :(得分:0)

在global.asax中使用GlobalFilters

GlobalFilters.Filters.Add(new SessionExpireFilterAttribute());

参考Dean Ward的最佳答案评论 Redirect to specific page after session expires (MVC4)

答案 3 :(得分:0)

我经常看到这样的解决方案:http://www.c-sharpcorner.com/UploadFile/91c28d/handle-session-expire-using-custom-attribute-in-Asp-Net-mvc/

在创建BaseController.cs控制器并定义OnActionExecuting方法之前。

public class BaseController : Controller
{

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        base.OnActionExecuting(filterContext);


        if (Session["UserLogin"] == null)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "ManageAccount" }, { "action", "Login" } });
        }
    }

}

在下一步中,创建HomeController.cs继承了BaseController.cs文件。

public class HomeController : BaseController
{
    // GET: Home
    public ActionResult Index()
    {  
        return View();
    }
}

BaseController OnActionExecuting方法处理每个请求并检查会话控制。

    [HttpPost]
    public ActionResult LoggedIn()
    {
        Session["UserLogin"] = true;

        return RedirectToAction("Index", "Home");
    }

创建示例登录发布方法,发送请求集UserLogin会话参数并重定向到Home / Index页面。您继承调用的每个控制器将对每个请求执行会话控制。

我希望它有所帮助。