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

本文关键字:会话 MVC 如果 重定向 登录 | 更新日期: 2023-09-27 18:11:08

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

        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
   }

那么现在我如何重定向他到登录页面,如果会话过期

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

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

    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. 在web中编写代码。配置文件将会话超时时间设置为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. 在布局的<script>标签中编写下面的代码。cshtml

    //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");
    }
    

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

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文件中注册这个过滤器。

因此,当会话过期时,就像会话中的值一样,您不需要检查某个特定的会话值是否已经过期。

你可以在全局的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" } });
            }
        }