creating absolute URLs that work on both localhost and live site

I want to populate a Literal control with a URL that will work on both my local machine and the live website.

For now, this is what I have:

string TheHost = HttpContext.Current.Request.Url.Host;
string ThePath = HttpContext.Current.Request.Url.AbsolutePath;
string TheProtocol = HttpContext.Current.Request.Url.Scheme;

string TheURL = "<a href=\"" + TheProtocol + "://" + TheHost + "/ThePageName\">SomeText</a>"

The URL that works when I type it manually in the browser looks like this:

http://localhost:12345/ThePageName

but when I run the above code it comes out as

localhost/ThePageName

What do I need to change so that on my local machine I output

http://localhost:12345/ThePageName

and on the live site I get

http://www.example.com/ThePageName

Thanks.

Jon Skeet
people
quotationmark

Use the fact that you've already got a Uri via the Request property - you don't need to do it all manually:

Uri pageUri = new Uri(HttpContext.Current.Request.Url, "/ThePageName");

Then build your tag using that - but ideally not just with string concatenation. We don't know enough about what you're using to build the response to say the best way to do it, but if you can use types which know how and when to use URI escaping etc, that will really help.

(I'd also suggest getting rid of your The prefix on every variable, but that's a somewhat different matter...)

people

See more on this question at Stackoverflow