获取没有查询字符串的网址

Roc*_*ngh 182 c# asp.net

我有这样的网址:

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

我想摆脱http://www.example.com/mypage.aspx它.

你能告诉我怎样才能得到它?

Joh*_*ika 364

这是一个更简单的解决方案:

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

借用于此:截断查询字符串并返回干净的URL C#ASP.net

  • 一行版本:`return Request.Url.GetLeftPart(UriPartial.Path);` (16认同)
  • `uri.GetComponent(` 是获取 Uri 部分的另一种很棒的方法。直到现在我才知道这两个! (2认同)

Jos*_*osh 129

您可以使用 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);
Run Code Online (Sandbox Code Playgroud)

或者你可以使用 substring

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

编辑:修改第一个解决方案,以反映评论中的brillyfresh的建议.

  • 如上所述,Uri.GetLeftPart方法更简单http://stackoverflow.com/questions/1188096/truncating-query-string-returning-clean-url-c-sharp-asp-net/1188180#1188180 (19认同)
  • url.AbsolutePath只返回URL的路径部分(/mypage.aspx); prepend url.Scheme(http)+ Uri.SchemeDelimiter(://)+ url.Authority(www.somesite.com)获取您想要的完整网址 (6认同)

小智 37

这是我的解决方案:

Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty);
Run Code Online (Sandbox Code Playgroud)

  • 如果没有查询字符串,这将给出错误 (8认同)

小智 33

Request.RawUrl.Split(new[] {'?'})[0];
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个只是因为你可以在没有完整的uri的情况下使用它. (2认同)

Abd*_*gab 31

好的答案也在这里找到答案的来源

Request.Url.GetLeftPart(UriPartial.Path)
Run Code Online (Sandbox Code Playgroud)


Sat*_*Sat 14

我的方式:

new UriBuilder(url) { Query = string.Empty }.ToString()
Run Code Online (Sandbox Code Playgroud)

要么

new UriBuilder(url) { Query = string.Empty }.Uri
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个,因为构建 URI 正是 UriBuilder 的用途。所有其他答案都是(好的)黑客。 (2认同)

Bra*_*don 10

您可以使用Request.Url.AbsolutePath获取页面名称以及Request.Url.Authority主机名和端口.我不相信有一个内置的属性可以准确地给你你想要的东西,但你可以自己组合它们.


Rai*_*ion 9

System.Uri.GetComponents,只需指定您想要的组件。

Uri uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);
Run Code Online (Sandbox Code Playgroud)

输出:

http://www.example.com/mypage.aspx
Run Code Online (Sandbox Code Playgroud)


Rob*_*rto 5

Split() 变体

我只想添加此变体以供参考。Urls 通常是字符串,因此使用该Split()方法比使用Uri.GetLeftPart(). 并且Split()还可以与相对的,空的,空值工作取得,而乌里抛出异常。此外,Urls 还可能包含一个散列,例如/report.pdf#page=10(在特定页面打开 pdf)。

以下方法处理所有这些类型的 Url:

   var path = (url ?? "").Split('?', '#')[0];
Run Code Online (Sandbox Code Playgroud)

示例输出:

  • 我很震惊,直到我自己才得到任何赞成。这是一个很好的解决方案。 (2认同)