I have a URL like this:
http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye
I want to get http://www.example.com/mypage
I've created a simple extension, as a few of the other answers threw null exceptions if there wasn't a QueryString
to start with:
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;
}
Usage:
var url = Request.Url?.AbsoluteUri.TrimQueryString()
This is my solution:
Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty);
Split() Variation
I just want to add this variation for reference. Urls are often strings and so it's simpler to use the Split()
method than Uri.GetLeftPart()
. And Split()
can also be made to work with relative, empty, and null values whereas Uri throws an exception. Additionally, Urls may also contain a hash such as /report.pdf#page=10
(which opens the pdf at a specific page).
The following method deals with all of these types of Urls:
var path = (url ?? "").Split('?', '#')[0];
Example Output:
http://domain/page.html#page=2 ---> http://domain/page.html
page.html ---> page.html
Solution for Silverlight:
string path = HtmlPage.Document.DocumentUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
You can use Request.Url.AbsolutePath
to get the page name, and Request.Url.Authority
for the host name and port. I don't believe there is a built in property to give you exactly what you want, but you can combine them yourself.
You can use 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);
Or you can use substring
string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.Substring(0, url.IndexOf("?"));
EDIT: Modifying the first solution to reflect brillyfresh's suggestion in the comments.