I have used HttpContext.Current.Request.ServerVariables["server_name"] to get the hostname in my mvc application. It throws an exception as follows: "Object reference not set to an instance of an object". Having this line in my controller. string serverHost = Helper.GetHost(); And Having this method in my helper class. accessed this method from my controller. Not an controller constructor. public static string GetHost() { var url = string.Empty; var ipaddress = string.Empty; var sslFlag = WebConfigurationManager.AppSettings["ssl"]; var iisFlag = WebConfigurationManager.AppSettings["iis"]; if (iisFlag.Equals("true", StringComparison.InvariantCultureIgnoreCase)) ipaddress = WebConfigurationManager.AppSettings["IpAddress"]; else ipaddress = HttpContext.Current.Request.UserHostAddress;
if (sslFlag.Equals("true", StringComparison.InvariantCultureIgnoreCase))
url = "https://";
else
url = "http://";
return url + ipaddress;
} Please let me know how to resolve the issue and suggest me a solution to get the hostname and port number in c#. Thanks in advance.