2017-09-18 40 views
-1
public static CustomerInfo Customer 
{ 
    get 
    { 
     if (System.Web.HttpContext.Current.Session["CustomerData"] == null) 
     {      
      System.Web.HttpContext.Current.Response.Redirect("~/Account/Login"); 
      return new CustomerInfo(); 
     } 
     else 
     { 
      return (CustomerInfo)System.Web.HttpContext.Current.Session["CustomerData"]; 
     } 
    } 
    set 
    { 
     System.Web.HttpContext.Current.Session["CustomerData"] = value; 
    } 
} 

每當HttpContext.Current.Session["CustomerData"]null,而不是重定向到登錄鑑於賬戶控制器它給例外。MVC5路由編程C#

+5

一個屬性的getter與副作用是一個壞主意。 – Amy

+0

使用[action filter](https://www.codeproject.com/Articles/1095295/Check-Session-Timeout-by-Using-ActionFilters-in-MV)檢查會話並重定向。 –

+0

感謝史蒂夫建議使用操作過濾器,但是可以將它重定向到getter的登錄視圖。 – Madhurima

回答

-1

嘗試:

if (System.Web.HttpContext.Current.Session["CustomerData"] == null) 
    {      
     Session["CustomerLogin"] = "True"; 
     return new CustomerInfo(); 
    } 
    else 
    { 
     Session["CustomerLogin"] = "False"; 
     return (CustomerInfo)System.Web.HttpContext.Current.Session["CustomerData"]; 
    } 

然後在你的控制器檢查:

if(Convert.ToString(Session["CustomerLogin"]) == "True"){ 
    return RedirectToAction("Login", "Account"); 
} 
+0

不能在他的實現中做到這一點 - 他試圖在他的靜態類的getter中做到這一點 - 它返回'CustomerInfo' – Alex

+0

哦,是的,你是對的。那麼他需要檢查什麼CustomerInfo返回並相應地重定向。 – Laiman

+0

嗨萊曼感謝您的回覆。但是這個公共的靜態方法是在公共類CustomerInformation中,它給出了RedirectToAction在當前上下文中不存在的例外 – Madhurima

0

您可以使用

Return RedirectToAction("Login", "Account"); 

重定向到另一個控制器和控制方法

+0

你不能這樣做。這是我首先想到的,但他試圖在他的靜態類的getter中完成此操作 - 它返回CustomerInfo() – Laiman