如何在C#中获取当前页面的URL

时间:2009-02-27 06:20:47

标签: c# asp.net

有谁能帮助我在C#中获取ASP.NET当前工作页面的URL?

9 个答案:

答案 0 :(得分:853)

试试这个:

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost

答案 1 :(得分:447)

您有时可能需要从网址获取不同的值。

下面的示例显示了提取网址的不同部分的不同方法

示例:(示例网址)

http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2

<强> CODE

Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Port);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);

<强>输出

localhost
localhost:60527
60527
/WebSite1test/Default2.aspx
/WebSite1test
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2

您可以复制上面的示例代码&amp;在具有不同URL的asp.net Web表单应用程序中运行它。

我还建议您阅读ASP.Net路由,以防您使用ASP路由,然后您不需要使用带有查询字符串的传统URL。

http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx

答案 2 :(得分:103)

由于这是我的解决方案,感谢Canavar的帖子。

如果你有这样的事情:

"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"

或者像这样:

"https://www.something.com/index.html?a=123&b=4567"

并且您只想要用户输入的部分然后这将起作用:

String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");

会导致这些:

"http://localhost:1234/"
"https://www.something.com/"

答案 3 :(得分:45)

如果您只想要http://和第一个斜杠之间的部分

string url = Request.Url.Host;
如果从此页面调用

将返回stackoverflow.com

这是complete breakdown

答案 4 :(得分:20)

request.rawurl将提供当前页面的内容 它提供了您需要的确切路径

使用HttpContext.Current.Request.RawUrl

答案 5 :(得分:14)

如果你想获得

localhost:2806 

来自

http://localhost:2806/Pages/ 

然后使用:

HttpContext.Current.Request.Url.Authority

答案 6 :(得分:12)

需要global.asax文件中的路径/网址的人的提示;

如果您需要在 global.asax&gt;中运行此功能Application_Start ,您的应用池模式已集成,您将收到以下错误:

  

请求在此上下文异常中不可用   的Application_Start

在这种情况下,你需要使用它:

  

<强> System.Web.HttpRuntime.AppDomainAppVirtualPath

希望能帮助别人..

答案 7 :(得分:9)

搜索让我看到了这个页面,但这并不是我想要的。发布此处以防其他人在此页面上查找我所登陆的内容。

如果你只有一个字符串值,有两种方法可以做到。

.NET方式:

与@Canavar相同,但您可以实例化一个新的Uri对象

String URL = "http://localhost:1302/TESTERS/Default6.aspx";
System.Uri uri = new System.Uri(URL);

表示您可以使用相同的方法,例如

string url = uri.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string host = uri.host
// localhost

正则表达方式:

Getting parts of a URL (Regex)

答案 8 :(得分:6)

我想它足以返回绝对路径..

 Path.GetFileName( Request.Url.AbsolutePath )

使用System.IO;