HttpContext.Current.Request.ServerVariables在c#中抛出空引用异常

时间:2016-11-15 05:24:34

标签: c#-4.0 httpcontext

我使用了HttpContext.Current.Request.ServerVariables [“server_name”]来获取我的mvc应用程序中的主机名。它抛出异常如下:“对象引用未设置为对象的实例”。在我的控制器中有这一行。 string serverHost = Helper.GetHost();并在我的帮助类中使用此方法。从我的控制器访问此方法。不是控制器构造函数。 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”];             其他                 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 个答案:

答案 0 :(得分:0)

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"]; }
}

我的虚拟应用程序中的这个简单代码。