2016-12-27 11 views
0

ASP.Net Webアプリケーションがあり、ブラウザに存在するURLを取得したいと思います。以下は私の試みASP.Net MVC 5アプリケーションのブラウザからURLを取得する方法

public static string UrlForGoogleAuth 
{ 
    get 
    { 
     UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); 

     string host = HttpContext.Current.Request.Url.Host; 
     if (host == "localhost") 
     { 
      host = HttpContext.Current.Request.Url.Authority; 
     } 
     string result = "https://" + host + url.Action("LoginSettingsSubmit", "Security"); 
     return result; 
    } 
} 

シナリオ1 URLです:https://sample.comは - 正常に動作してhost variablesample.com

シナリオ2.のURLフェッチ:https://sample.com:2345からhost variableはちょうどsample.com代わりのsample.com:2345

をフェッチしますWork Around(一時的な修正:結果にハードコード2345)

string result = "https://" + host + ":2345" + url.Action("LoginSettingsSubmit", "Security"); 

しかし、私はハードコーディングのない馬鹿な解決策を探しています。また、既に書かれたコードの内容を変更することなく結果を達成できれば、それは素晴らしいことです。

EDIT: 

    public static string UrlForGoogleAuth 
    { 
     get 
     { 
      UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); 
       host = HttpContext.Current.Request.Url.Authority; 
      string result = "https://" + host + url.Action("LoginSettingsSubmit", "Security"); 
      return result; 
     } 
    } 
+0

なぜあなただ​​け 'localhost'ためUrl.Authority''に 'host'を設定していますか?いつも 'Url.Authority'を使ってみませんか?そして、__Scenario 1__では、https://sample.comの 'Host'がabc.comだったら驚いています。 –

+0

私は初心者です。私の無知を許してください。私はあなたが話したことをやろうとし、私が欲しいものを手に入れたら教えてくれるでしょう。 – Unbreakable

+0

abcはtypoでした。ありがとう。それを固定した。 – Unbreakable

答えて

1

Uri.Authorityはあなたのホスト名とポートを与えます。

サーバーのDNS(ドメインネームシステム)ホスト名またはIPアドレスとポート番号( )を取得します。

// www.sample.com:8080 
Console.WriteLine(new Uri("https://www.sample.com:8080/controller/action").Authority); 

// www.sample.com 
Console.WriteLine(new Uri("https://www.sample.com/controller/action").Authority); 

だからあなたの場合には、あなただけの次を使用します。

HttpContext.Current.Request.Url.Authority 
+1

ありがとうございました。私は "無知は今のところ禁じられている"ことを覚えています:):D:D – Unbreakable

1

これは、あなたの完全なURLを提供します:(URLは1を持っている場合)

var url = Request.RequestContext.HttpContext.Request.RawUrl; 
関連する問題