boot4life
boot4life

Reputation: 5324

What to use as the key in a custom TempData provider?

I'm investigating storing TempData in a better place. There is a walkthrough for how to do that with MongoDB but the key used for storage (item.SessionIdentifier == controllerContext.HttpContext.Request.UserHostAddress, the IP address) is clearly not working because multiple users/sessions can share the same public IP.

The consequence of using the IP as the key is that multiple users will see (and delete) each others data. In particular, during testing on your dev machine all sessions and browser instances will share the same temp data.

What would be a good key to use for TempData storage in some database?

Upvotes: 0

Views: 238

Answers (1)

Vinutha N
Vinutha N

Reputation: 166

Instead of assigning to tempdata directly call below method when ever assigning to object

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

Upvotes: 0

Related Questions