1

I have two string:

string url = HttpContext.Current.Request.Url.AbsoluteUri;
//give me :
//url = http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15

And:

string path = HttpContext.Current.Request.Url.AbsolutePath;
//give me:
//path = /TESTERS/Default6.aspx

Now I want to get the string:

http://localhost:1302

So what I am thinking of is I will find the position of path in url and remove the sub-string from this position in url. What I tried:

string strApp = url.Remove(url.First(path));

or

string strApp = url.Remove(url.find_first_of(path));

but I can't find the write way to express this idea. How can I archive my goal?

1
  • 1
    Note that answer that provides correct handling of all sorts of urls is "use UriBuilder", so see if you get one later. Commented Jun 4, 2014 at 3:50

5 Answers 5

3

So basically you want the URL, from the start up to the beginning of your path.

You don't need to "remove" that part, only take characters up to that precise point. First, you can get that location with a simple IndexOf as it returns the position of the first character that matches your string. After this, simply take the part of url that goes from 0 to that index with Substring.

string url = "http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15";
string path = "/TESTERS/Default6.aspx";
int indexOfPath = url.IndexOf(path);
string strApp = url.Substring(0, indexOfPath); // gives http://localhost:1302

Which you can shorten to

string strApp = url.Substring(0, url.IndexOf(path));
Sign up to request clarification or add additional context in comments.

Comments

0

you can also do something like below code to get the Host of URI

Uri uri =HttpContext.Current.Request.Url.AbsoluteUri ; string host = uri.Authority; // "example.com"

Comments

0

Here is another option.. this doesn't require any string manipulation:

new Uri(HttpContext.Current.Request.Url, "/").AbsoluteUri

It generates a new Uri which is the path "/" relative to the original Url

Comments

0

You should just use this instead:

string baseURL = HttpContext.Current.Context.Request.Url.Scheme + "://" +
      HttpContext.Current.Context.Request.Url.Authority;

Comments

0

This should not be solved using string manipulation. HttpContext.Current.Request.Url returns an Uri object which has capabilities to return the information you request.

var requestUrl = HttpContext.Current.Request.Url;
var result = requestUrl.GetComponents(UriComponents.SchemeAndServer,
                                      UriFormat.Unescaped);
// result = "http://localhost:1302"

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.