2017-04-26 87 views
0

我正在調查存儲TempData在一個更好的地方。有一個walkthrough for how to do that with MongoDB,但用於存儲的密鑰(item.SessionIdentifier == controllerContext.HttpContext.Request.UserHostAddress,IP地址)顯然不起作用,因爲多個用戶/會話可以共享相同的公共IP。什麼用作自定義TempData提供程序中的鍵?

使用IP作爲關鍵的結果是多個用戶將看到(和刪除)其他數據。特別是,在您的開發機器上進行測試期間,所有會話和瀏覽器實例將共享相同的臨時數據。

什麼是在某些數據庫中使用TempData存儲的好鑰匙?

回答

0

不是指定直接TempData的撥打以下方法時曾經分配給對象

public static string GetVisitorIPAddress(bool GetLan = false) 
     { 
      string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 

      if (String.IsNullOrEmpty(visitorIPAddress)) 
       visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; 

      if (string.IsNullOrEmpty(visitorIPAddress)) 
       visitorIPAddress = HttpContext.Current.Request.UserHostAddress; 

      if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1") 
      { 
       GetLan = true; 
       visitorIPAddress = string.Empty; 
      } 

      if (GetLan && string.IsNullOrEmpty(visitorIPAddress)) 
      { 
       //This is for Local(LAN) Connected ID Address 
       string stringHostName = Dns.GetHostName(); 

       //Get Ip Host Entry 
       IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName); 

       //Get Ip Address From The Ip Host Entry Address List 
       IPAddress[] arrIpAddress = ipHostEntries.AddressList; 

       try 
       { 
        visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString(); 
       } 
       catch 
       { 
        try 
        { 
         visitorIPAddress = arrIpAddress[0].ToString(); 
        } 
        catch 
        { 
         try 
         { 
          arrIpAddress = Dns.GetHostAddresses(stringHostName); 
          visitorIPAddress = arrIpAddress[0].ToString(); 
         } 
         catch 
         { 
          visitorIPAddress = "127.0.0.1"; 
         } 
        } 
       } 
      } 

      return visitorIPAddress.Split(',')[0].Trim(); 
     } 
+0

多個用戶可以共享一個IP地址。在同一臺計算機上至少有不同的瀏覽器。 – boot4life

+0

TempData是會話綁定的。相應的用戶將只能看到它的TempData。 –

+0

TempData綁定到提供者綁定到的地方。 MVC系統不能讓提供者特別做任何事情,並依靠它來爲正確的用戶/會話或任何其他範圍正在使用(在此代碼中是IP,而不是會話)返回正確的數據。 – boot4life

相關問題