0
votes

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.
1
Where are you using this?? - Abdul Khan
I have used it in the Helper.cs class file and invoked the method from the controller. - mRhNs13
Using it in Controller Constructor ?? - Abdul Khan
string serverHost = Helper.GetHost(); - mRhNs13
yes Abdul Khan. Its a field in the controller.Its not inside the action method. - mRhNs13

1 Answers

0
votes
public class HomeController : Controller
{
    string serverHost = Helper.GetHost();
    public ActionResult Index()
    {
        var t = serverHost;
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        return View();
    }
}
public static class Helper
{
    public static string GetHost() { return HttpContext.Current.Request.ServerVariables["server_name"]; }
}

This simple Code in my Dummy Application Works.