Tuesday, March 20, 2012

How to get client IP Address in MVC3?

Before implementing this I did so many things but not succeed like this to get the client Ip address means from where the browser open. In one of my project i have to save the client IP address, browser name  and browser version. Its a MVC 3 razor application.
  So here i am showing you how to get these

        public static string GetIPAddress(HttpRequestBase request)
        {
            string ip = string.Empty;
            try
            {
                ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (!string.IsNullOrEmpty(ip))
                {
                    if (ip.IndexOf(",") > 0)
                    {
                        string[] allIps = ip.Split(',');
                        int le = allIps.Length - 1;
                        ip = allIps[le];
                    }
                }
                else
                {
                    ip = request.UserHostAddress;
                }      
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return ip;
        }

         public static string GetBrowserType(HttpRequestBase request)
        {
            try
            {
                HttpContext.Current.Session["BrowserType"] = request.Browser.Browser;
              
                return HttpContext.Current.Session["BrowserType"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

         public static string GetBrowserVesrsion(HttpRequestBase request)
        {
            try
            {
                HttpContext.Current.Session["BrowserVesrsion"] = request.Browser.MajorVersion;

                return HttpContext.Current.Session["BrowserVesrsion"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

No comments:

Post a Comment