簡體   English   中英

如果會話在 MVC 中不可用,如何重定向到登錄頁面

[英]How to redirect to login page if session is not available in 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
   }

那么現在如果會話過期,我如何將他重定向到登錄頁面

我認為您可以將此邏輯包裝在動作過濾器中,並在那里重定向:

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

您應該創建一個自定義過濾器屬性來處理會話到期,如下所示 -

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM