Asp.net-Mvc-4

會話到期後重定向到特定頁面(MVC4)

  • May 24, 2019

C# MVC4 項目:我想在會話到期時重定向到特定頁面。

經過一番研究,我在我的項目中添加了以下程式碼Global.asax

protected void Session_End(object sender, EventArgs e)
{
    Response.Redirect("Home/Index");
}

當會話到期時,它會在該行拋出一個Response.Redirect("Home/Index");異常The response is not available in this context

這裡有什麼問題?

MVC 中最簡單的方法是在會話過期的情況下,在每個操作中您必須檢查其會話,如果它為空,則重定向到索引頁面。

為此,您可以製作如下所示的自定義屬性:-

這是覆蓋 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);
       }
   }

然後在行動中添加這個屬性,如圖所示:

[SessionExpire]
public ActionResult Index()
{
    return Index();
}

或者只添加一次屬性:

[SessionExpire]
public class HomeController : Controller
{
 public ActionResult Index()
 {
    return Index();
 }
}

引用自:https://stackoverflow.com/questions/25423464