Carol
Carol

Reputation: 271

Get absolute Url in asp.net

When I'm running my website with visual studio, its root url is: http://localhost:4657

I have strings containing paths like ~/Login.aspx and I need to concatenate them so that the return will be http://localhost:4657/Login.aspx.

I can see a lot of ways to do this, but what is the right way?

Upvotes: 2

Views: 17911

Answers (3)

Chris Foster
Chris Foster

Reputation: 1300

This is what I use

var baseUri = new Uri(HttpContext.Current.Request.Url, "/");

Upvotes: 0

Aditya Bokade
Aditya Bokade

Reputation: 1786

How about Request.Url? Url.Authority provides host name or Socket(IPAddress:PortNo) and segments provide other parts of URL. Just omit the LAST segment as it contains the current page's name. Hence i-1*.

    string myurl = "http://"+Request.Url.Authority;
    for(int i=0;i<Request.Url.Segments.Length-1;i++)
    {
        myurl = myurl + Request.Url.Segments[i];
    }
    myurl = myurl + "login.aspx";
    Response.Redirect(myurl);

Upvotes: 2

BrandonZeider
BrandonZeider

Reputation: 8152

Try Page.ResolveUrl.

string url = Page.ResolveUrl("~/Login.aspx");

If you need a complete URL, say to email it or something, take a look at this blog post.

Upvotes: 7

Related Questions