2016-11-15 152 views
0

我已經使用HttpContext.Current.Request.ServerVariables [「server_name」]在我的mvc應用程序中獲取主機名。它引發一個異常,如下所示:「對象引用未設置爲對象的實例」。在我的控制器中有這條線。字符串serverHost = Helper.GetHost();並在我的助手類中使用此方法。從我的控制器訪問此方法。不是控制器構造函數。公共靜態字符串GetHost() { var url = string.Empty; var ipaddress = string.Empty; var sslFlag = WebConfigurationManager.AppSettings [「ssl」]; var iisFlag = WebConfigurationManager.AppSettings [「iis」];如果(iisFlag.Equals(「true」,StringComparison.InvariantCultureIgnoreCase)) ipaddress = WebConfigurationManager.AppSettings [「IpAddress」]; else ipaddress = HttpContext.Current.Request.UserHostAddress;HttpContext.Current.Request.ServerVariables在c#中拋出空引用異常#

 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. 
+0

你在哪裏使用? –

+0

我在Helper.cs類文件中使用了它,並從控制器調用了該方法。 – mRhNs13

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

這個簡單的代碼在我的虛擬應用程序的工作。