2016-11-15 21 views
0

私は、mvcアプリケーションでホスト名を取得するためにHttpContext.Current.Request.ServerVariables ["server_name"]を使用しました。次のように例外がスローされます。 "オブジェクト参照がオブジェクトのインスタンスに設定されていません"。私のコントローラーにこの行がある。文字列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"]; else ipaddress = HttpContext.Current.Request.UserHostAddress;HttpContext.Current.Request.ServerVariablesがnull参照例外をスローしました。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"]; } 
} 

私のダミーアプリケーションの動作中にこの単純なコード。

関連する問題