如果会话在MVC中不可用,如何重定向到登录页面

时间:2015-09-03 18:18:59

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

我正在开发ASP.Net MVC 5.0应用程序,。现在我已经创建了登录页面。当用户有效时,我将用户详细信息存储到seesion中。

        if(_loginmodel.authstatus == false)
        {
            return View("Index");
        }

        Session["authstatus"] = true;
        Session["userid"] = _loginmodel.userid;
        Session["useremail"] = _loginmodel.useremail;
        Session["username"] = _loginmodel.username;

当用户转到其他文件时,我再次检查会话是否可用

  public class CityController : Controller
    {

    private CityModels _citymodel;

    #region Constructor
    public CityController()
    {
        if (Session != null && Session["authstatus"] != null)
        {
            _citymodel = new CityModels();

        }
        RedirectToAction("Index", "Login");
    }
    #endregion
   }

所以,如果会话过期,我怎样才能将他重定向到登录页面

4 个答案:

答案 0 :(得分:6)

我认为你可以将这个逻辑包装在一个动作过滤器中,并在那里重定向:

    public class AuthorizeActionFilterAttribute : ActionFilterAttribute
    {
      public override void OnActionExecuting(FilterExecutingContext filterContext)
      {
        HttpSessionStateBase session = filterContext.HttpContext.Session;
        Controller controller = filterContext.Controller as Controller;

        if (controller != null)
        {
          if (session != null && session ["authstatus"] == null)
          {
filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "Login" },
                                          { "action", "Index" }

                                         });
          }
        }

        base.OnActionExecuting(filterContext);
      }
    }

这里有更多细节:

https://stackoverflow.com/a/5453371/1384539

答案 1 :(得分:3)

  1. 在web.config文件中编写代码,将会话超时设置为2分钟

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Forms">
            <forms loginUrl="~/Login/Index" timeout="1" />
        </authentication>
        <sessionState timeout="2"></sessionState>
        <globalization uiCulture="en" culture="en-GB"/>
    </system.web>
    
  2. 将以下代码编写在layout.cshtml

    中的<script>标记中
    //session end 
    var sessionTimeoutWarning = @Session.Timeout - 1;
    var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
    setTimeout('SessionEnd()', sTimeout);
    
    function SessionEnd() {
        window.location.hostname = "";
        /* $(window.Location).attr("href", "@Url.Content("~/Login/index/")"); */
        window.location = "/Login/index/";
    }
    
  3. 在控件和操作中编写以下代码

    [HttpGet]
    public ActionResult Logout()
    { 
        Session["id1"] = null;
        Session["id2"] = null;
        Session["id3"] = null;
        Session["id4"] = null;
        Session["Region"] = null;
        Session.Clear();           
        Session.RemoveAll();
        Session.Abandon();
        Response.AddHeader("Cache-control", "no-store, must-revalidate, private, no-cache");
        Response.AddHeader("Pragma", "no-cache");
        Response.AddHeader("Expires", "0");
        Response.AppendToLog("window.location.reload();");
    
        return RedirectToAction("Index", "Login");
    }
    

答案 2 :(得分:0)

您应该创建自定义过滤器属性来处理会话过期,如下所示 -

public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    /// <summary>
    /// Custom attribute for handling session timeout
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        // check if session is supported
        if (ctx.Session != null)
        {
            // check if a new session id was generated
            if (ctx.Session.IsNewSession)
            {
                // If it says it is a new session, but an existing cookie exists, then it must
                // have timed out
                string sessionCookie = ctx.Request.Headers["Cookie"];
                if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    ctx.Response.Redirect("~/Error/SessionTimeoutVeiw");
                }
            }
        }
        base.OnActionExecuting(filterContext);
    }
}

现在要使用此自定义属性,请使用此属性修饰控制器方法或类。

[SessionExpireFilterAttribute]

如果您需要将此过滤器应用于所有控制器,则可以在FilterConfig文件中注册此过滤器。

因此,当会话到期时,以及会话中的值,您无需检查特定会话值是否已过期。

答案 3 :(得分:0)

您可以在Global

中的Session_Start事件上将用户重定向到登录页面
protected void Session_Start()
        {            
            if (Session["Username"] != null)
            {
                //Redirect to Welcome Page if Session is not null  
                HttpContext.Current.Response.Redirect("~/WelcomeScreen", false);

            }
            else
            {
                //Redirect to Login Page if Session is null & Expires                   
                new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Login" } });
            }
        }