我有一个这样的URL:
http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye
我想从中得到http://www.example.com/mypage.aspx。
你能告诉我怎么买吗?
我有一个这样的URL:
http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye
我想从中得到http://www.example.com/mypage.aspx。
你能告诉我怎么买吗?
当前回答
这里有一个更简单的解决方案:
var uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = uri.GetLeftPart(UriPartial.Path);
借用这里:截断查询字符串和返回干净的URL c# ASP.net
其他回答
好的答案也在这里找到了答案来源
Request.Url.GetLeftPart(UriPartial.Path)
简单的例子是使用子字符串:
string your_url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path_you_want = your_url .Substring(0, your_url .IndexOf("?"));
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);
输出:
http://www.example.com/mypage.aspx
我的方法:
new UriBuilder(url) { Query = string.Empty }.ToString()
or
new UriBuilder(url) { Query = string.Empty }.Uri
我已经创建了一个简单的扩展,因为其他一些答案抛出空异常,如果没有QueryString开始:
public static string TrimQueryString(this string source)
{
if (string.IsNullOrEmpty(source))
return source;
var hasQueryString = source.IndexOf('?') != -1;
if (!hasQueryString)
return source;
var result = source.Substring(0, source.IndexOf('?'));
return result;
}
用法:
var url = Request.Url?.AbsoluteUri.TrimQueryString()