我有這樣一個URL:獲取URL查詢字符串不
http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye
我想從它那裏得到http://www.example.com/mypage.aspx
。
你能告訴我如何得到它嗎?
我有這樣一個URL:獲取URL查詢字符串不
http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye
我想從它那裏得到http://www.example.com/mypage.aspx
。
你能告訴我如何得到它嗎?
您可以使用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的在評論中建議。
您可以使用Request.Url.AbsolutePath
獲取頁面名稱,使用Request.Url.Authority
獲取主機名和端口。我不相信有一個內置的財產給你你想要的東西,但你可以自己結合它們。
這是給我/mypage.aspx,不是我想要的東西。 – 2011-01-07 21:07:25
這裏有一個簡單的解決方案:
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
Request.RawUrl.Split(new[] {'?'})[0];
這是我的解決方案:
Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty);
我的方式:
new UriBuilder(url) { Query = string.Empty }.ToString()
或
new UriBuilder(url) { Query = string.Empty }.Uri
這是一個使用@ KOLMAN的答案的擴展方法。記住使用Path()比GetLeftPart稍微容易一些。您可能希望將Path重命名爲GetPath,至少在將擴展屬性添加到C#之前。
用法:
Uri uri = new Uri("http://www.somewhere.com?param1=foo¶m2=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);
}
}
}
Request.RawUrl.Split( '?')[0]
僅僅是出於URL名稱!
試試這個:
urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))
從這個:http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye 你會得到這樣的:mypage.aspx
this.Request.RawUrl.Substring(0,this.Request.RawUrl.IndexOf( 「?「))
很好的回答也在這裏source of answer
Request.Url.GetLeftPart(UriPartial.Path)
解決方案的Silverlight發現:
string path = HtmlPage.Document.DocumentUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
url.AbsolutePath只返回URL的路徑部分(/mypage.aspx); pre-url.Scheme(http)+ Uri.SchemeDelimiter(://)+ url.Authority(www.somesite.com)爲您需要的完整網址 – Ryan 2011-01-08 02:09:46
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