Request.URL for local and live site

I have a local host and a live site. I have a url, and if it should go to localhost url localhost / site / thank_you.aspx, and if its live http://mylivesite.com/thank_you.aspx

I tried this in my code behind ...

MyHiddenField.Value = Request.URL + "/thank_you.aspx";

but he returned the page I was on / thank _you.aspx

What am I doing wrong?

+5
source share
3 answers

Try it, I even added a scheme too, just in case you want https :)

EDIT: port added (thanks Alex) to be super-duper of the super future:

MyHiddenField.Value = string.Format(
    "{0}://{1}{2}/thank_you.aspx",  
    Request.Url.Scheme, 
    Request.Url.Host,
    Request.Url.IsDefaultPort ? string.Empty : ":" + Request.Url.Port);

EDIT: Another good suggestion from @MikeSmithDev by putting it in a function

public string GetUrlForPage(string page)
{
    return MyHiddenField.Value = string.Format(
       "{0}://{1}{2}/{3}",  
        Request.Url.Scheme, 
        Request.Url.Host,
        Request.Url.IsDefaultPort ? string.Empty : ":" + Request.Url.Port,
        page);
}

Then you can do:

MyHiddenField.Value = GetUrlForPage("thank_you.aspx");
+8
source

There is a built-in class UriBuilder

var url = Request.Url;
var newurl = new UriBuilder(url.Scheme, url.Host, url.Port, "thank_you.aspx")
                 .ToString();
+2

. . : ~/ ~/test/default.aspx

public string GetUrlForPage(string relativeUrl)
{
    return string.Format(
       "{0}://{1}{2}{3}",
        Request.Url.Scheme,
        Request.Url.Host,
        Request.Url.IsDefaultPort ? string.Empty : ":" + Request.Url.Port,
        Page.ResolveUrl(relativeUrl));
}
0

All Articles