2011-01-07 127 views
147

我有這樣一個URL:獲取URL查詢字符串不

http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye

我想從它那裏得到http://www.example.com/mypage.aspx

你能告訴我如何得到它嗎?

回答

112

您可以使用System.Uri

Uri url = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye"); 
string path = String.Format("{0}{1}{2}{3}", url.Scheme, 
    Uri.SchemeDelimiter, url.Authority, url.AbsolutePath); 

或者你可以使用substring

string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye"; 
string path = url.Substring(0, url.IndexOf("?")); 

編輯:修改第一個解決方案,以反映brillyfresh的在評論中建議。

+6

url.AbsolutePath只返回URL的路徑部分(/mypage.aspx); pre-url.Scheme(http)+ Uri.SchemeDelimiter(://)+ url.Authority(www.somesite.com)爲您需要的完整網址 – Ryan 2011-01-08 02:09:46

+16

Uri.GetLeftPart方法更簡單,如前所述http://stackoverflow.com/questions/1188096/truncating-query-string-returning-clean-url-c-sharp-asp-net/1188180#1188180 – 2011-12-19 14:39:06

10

您可以使用Request.Url.AbsolutePath獲取頁面名稱,使用Request.Url.Authority獲取主機名和端口。我不相信有一個內置的財產給你你想要的東西,但你可以自己結合它們。

+1

這是給我/mypage.aspx,不是我想要的東西。 – 2011-01-07 21:07:25

307

這裏有一個簡單的解決方案:

var uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye"); 
string path = uri.GetLeftPart(UriPartial.Path); 

從這裏借:Truncating Query String & Returning Clean URL C# ASP.net

+23

這應該是被接受的答案。 – 2013-12-10 21:00:57

+9

單行版本:`返回Request.Url.GetLeftPart(UriPartial.Path);` – jp2code 2016-09-01 19:10:51

+0

`uri.GetComponent(`是另一種獲取Uri部分的可靠方法,至今我都不知道這兩個! – AaronLS 2017-10-19 21:06:11

28
Request.RawUrl.Split(new[] {'?'})[0]; 
33

這是我的解決方案:

Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty); 
11

我的方式:

new UriBuilder(url) { Query = string.Empty }.ToString() 

new UriBuilder(url) { Query = string.Empty }.Uri 
3

這是一個使用@ KOLMAN的答案的擴展方法。記住使用Path()比GetLeftPart稍微容易一些。您可能希望將Path重命名爲GetPath,至少在將擴展屬性添加到C#之前。

用法:

Uri uri = new Uri("http://www.somewhere.com?param1=foo&param2=bar"); 
string path = uri.Path(); 

類:

using System; 

namespace YourProject.Extensions 
{ 
    public static class UriExtensions 
    { 
     public static string Path(this Uri uri) 
     { 
      if (uri == null) 
      { 
       throw new ArgumentNullException("uri"); 
      } 
      return uri.GetLeftPart(UriPartial.Path); 
     } 
    } 
} 
1

Request.RawUrl.Split( '?')[0]

僅僅是出於URL名稱!

-1

this.Request.RawUrl.Substring(0,this.Request.RawUrl.IndexOf( 「?「))

25

很好的回答也在這裏source of answer

Request.Url.GetLeftPart(UriPartial.Path) 
0

解決方案的Silverlight發現:

string path = HtmlPage.Document.DocumentUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);