frenchie
frenchie

Reputation: 52037

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

Upvotes: 0

Views: 1603

Answers (5)

user2557841
user2557841

Reputation:

Just use different key/value in web.config and web.release.config files, and whenever you have to use it, read them from the web.config file.

Here is the example web.config:

    <add key="Url" value="http://localhost:58980/" />

Here is the example web.release.config:

    <add key="Url" value="http://example.com/" xdt:Transform="Replace" xdt:Locator="Match(key)"/>

This may work. Works for me.

Upvotes: 0

Mehdi Souregi
Mehdi Souregi

Reputation: 3265

Or Uri pageUri = new Uri(HttpContext.Current.Request.Url, "ThePageName"); without anti-slash

Upvotes: 0

Phill
Phill

Reputation: 18804

I don't believe you need to add the hostname for any of your urls in your site.

Just make all your url's relative to the root:

string TheURL = "<a href=\"/ThePageName\">SomeText</a>"

or

string TheURL = "<a href=\"/Products/12345\">SomeText</a>"

This will work fine regardless of the hostname.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503290

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

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

Use UriBuilder to modify Urls. Assuming you need to just change path and keep all other parts the same:

var builder = new UriBuilder(HttpContext.Current.Request.Url);
builder.Path = "MyOtherPage";
return builder.Uri;

Upvotes: 1

Related Questions