240

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.aspx from it.

Can you tell me how can I get it?

21 Answers 21

446

Here's a simpler solution:

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

Borrowed from here: Truncating Query String & Returning Clean URL C# ASP.net

Sign up to request clarification or add additional context in comments.

2 Comments

One line version: return Request.Url.GetLeftPart(UriPartial.Path);
uri.GetComponent( is another awesome method for getting parts of a Uri. I didn't know about these two until now!
143

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.

3 Comments

url.AbsolutePath only returns the path portion of the URL (/mypage.aspx); prepend url.Scheme (http) + Uri.SchemeDelimiter (://) + url.Authority (www.somesite.com) for the full URL that you wanted
Uri.GetLeftPart method is simpler as mentioned stackoverflow.com/questions/1188096/…
The substring method will give error if there's no Query string. Use string path = url.Substring(0, url.IndexOf("?") > 0? url.IndexOf("?") : url.Length); instead.
43

This is my solution:

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

Comments

39

Good answer also found here source of answer

Request.Url.GetLeftPart(UriPartial.Path)

Comments

38

Succinct solution:

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

2 Comments

I like this just for the fact you can use it without a full uri.
Keep in mind that RawUrl will get the URL before URL rewrites, so perhaps use AbsoluteUri? Request.Url.AbsoluteUri.Split('?')[0]
16

My way:

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

or

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

2 Comments

This is what i use for NET Core 1.0 project because it has not method Uri.GetLeftPart. Latest version of NET Core (1.1) should have that method (cant confirm because i'm not on net core 1.1 for now)
I like this one because building URIs is exactly what the UriBuilder is for. All the other answers are (good) hacks.
11

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.

1 Comment

It is giving me /mypage.aspx , not what I wanted.
11

System.Uri.GetComponents, just specified components you want.

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

Output:

http://www.example.com/mypage.aspx

Comments

7

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:

1 Comment

I'm rather shocked this hasn't gotten any upvotes until my own. This is a great solution.
3

Here's an extension method using @Kolman's answer. It's marginally easier to remember to use Path() than GetLeftPart. You might want to rename Path to GetPath, at least until they add extension properties to C#.

Usage:

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

The class:

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);
        }
    }
}

Comments

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

Just for url name only !!

Comments

1
    string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
    string path = url.split('?')[0];

Comments

0

Solution for Silverlight:

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

Comments

0

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() 

Comments

0

.net core get url without querystring

var url = Request.GetDisplayUrl().Replace(Request.QueryString.Value.ToString(), "");

Comments

0

Cast the string to a Uri object first.

The query is in Uri.Query, you can just replace it to "" to get rid of it.

uri.ToString().Replace(uri.Query, "")

Comments

0

If you are using Blazor and .Net 8 you can get URL without query with NavigationManager.

var currentUrl = NavigationManager.ToAbsoluteUri(NavigationManager.Uri).GetLeftPart(UriPartial.Path);

Comments

-1

simple example would be using substring like :

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

Comments

-1
var canonicallink = Request.Url.Scheme + "://" + Request.Url.Authority + Request.Url.AbsolutePath.ToString();

Comments

-2

Try this:

urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))

from this: http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye you'll get this: mypage.aspx

Comments

-3
this.Request.RawUrl.Substring(0, this.Request.RawUrl.IndexOf('?'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.