C# で現在のページの完全な URL を取得するにはどうすればよいですか

StackOverflow https://stackoverflow.com/questions/40680

  •  09-06-2019
  •  | 
  •  

質問

ユーザー コントロールから現在のページの完全な URL を取得できる必要があります。多数の Request 変数を連結するだけなのでしょうか?もしそうならどれですか?それとももっと簡単な方法はありますか?

役に立ちましたか?

解決

私が普段使っているのは Request.Url.ToString() 完全な URL (クエリ文字列を含む) を取得するには、連結は必要ありません。

他のヒント

この種の情報を得るために私が通常参照するリストは次のとおりです。

Request.ApplicationPath :   /virtual_dir
Request.CurrentExecutionFilePath :  /virtual_dir/webapp/page.aspx
Request.FilePath :  /virtual_dir/webapp/page.aspx
Request.Path :  /virtual_dir/webapp/page.aspx
Request.PhysicalApplicationPath :   d:\Inetpub\wwwroot\virtual_dir\
Request.QueryString :   /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.AbsolutePath :  /virtual_dir/webapp/page.aspx
Request.Url.AbsoluteUri :   http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Host :  localhost
Request.Url.Authority : localhost:80
Request.Url.LocalPath : /virtual_dir/webapp/page.aspx
Request.Url.PathAndQuery :  /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Port :  80
Request.Url.Query : ?q=qvalue
Request.Url.Scheme :    http
Request.Url.Segments :  /
    virtual_dir/
    webapp/
    page.aspx

これが役立つことを願っています。

Request.Url.AbsoluteUri

このプロパティは、必要なすべてを 1 回の簡潔な呼び出しで実行します。

Request.RawUrl

http からクエリ文字列までのすべてとして完全な URL が必要な場合は、次の変数を連結する必要があります。

Request.ServerVariables("HTTPS") // to check if it's HTTP or HTTPS
Request.ServerVariables("SERVER_NAME") 
Request.ServerVariables("SCRIPT_NAME") 
Request.ServerVariables("QUERY_STRING")

のために ASP.NET Core それを詳しく説明する必要があります:

@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}{Context.Request.QueryString}")

または、ビューに using ステートメントを追加することもできます。

@using Microsoft.AspNetCore.Http.Extensions

それから

@Context.Request.GetDisplayUrl()

_ViewImports.cshtml そのためにはもっと良い場所かもしれない @using

使った方が良い Request.Url.OriginalString よりも Request.Url.ToString() (によると MSDN)

ありがとう、私はあなたの答え@Christianと@Jonathanの両方を組み合わせて、私の特定のニーズに対応しました。

"http://" + Request.ServerVariables["SERVER_NAME"] +  Request.RawUrl.ToString()

安全な http について心配する必要はありません。servername 変数が必要で、RawUrl はドメイン名からのパスを処理し、存在する場合はクエリ文字列を含みます。

ポート番号も必要な場合は、次を使用できます

Request.Url.Authority

例:

string url = Request.Url.Authority + HttpContext.Current.Request.RawUrl.ToString();

if (Request.ServerVariables["HTTPS"] == "on")
{
    url = "https://" + url;
}
else 
{
    url = "http://" + url;
}

次のことを試してください -

var FullUrl = Request.Url.AbsolutePath.ToString();
var ID = FullUrl.Split('/').Last();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top