views:

47

answers:

3

In ASP.NET I'd like to create a link which points to a specific Uri and send this link in an email to a user, for instance something like http://www.BlaBla.com/CustomerPortal/Order/9876. I can create the second part of the Uri /CustomerPortal/Order/9876 dynamically in code-behind. My question is: How can I create the base Uri http://www.BlaBla.com without hardcoding it in my application? Basically I want to have something like:

http://localhost:1234/CustomerPortal/Order/9876 (on my development machine)
http://testserver/CustomerPortal/Order/9876 (on an internal test server)
http://www.BlaBla.com/CustomerPortal/Order/9876 (on the production server)

So is there a way to ask the server where the application is running: "Please tell me the base Uri of the application" ? Or any other way?

Thank you in advance!

+1  A: 

What about to place it into the web.config

<configuration>
    <appSettings>
       <add key="SendingUrlBase" value="http://www.BlaBla.com"/&gt;
Dewfy
Good and easy solution! Thank you!
Slauma
@Slauma you are welcome
Dewfy
+1  A: 

Something like this:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath.TrimEnd('/')
Frederik Vig
+1  A: 

You have to put a key in config, something somewhere, because when you think about your web application, it's not really tied to a URL. For example:

http://localhost:1234/
http://yourMachineName:1234/
http://yourMachineName.domain.com:1234/
http://127.0.0.1:1234/

These are just a few ways to get to the same site on localhost....which is it? The same problem exists in production, dozens of domains or IPs may point to the same web application, and it uses host headers or maybe nothing to distinguish it. The point is, when outside the context of a request, the site doesn't really know what URL it goes with, could be anything, there's just not a 1:1 relation there.

If you are in the context of a request when sending an email, then take a look at HttpRequest.Url, this is a Uri type, and you can see the available properties here.

You can do something like this:

var host = HttpContext.Current.Url.Host;
//generate your link using the host
Nick Craver
Thanks, good explanation, especially the point that the relation between site and URL is not unique. I will probably go with Dewfy's proposal to have a general solution for situations where I am in the context of a request or not. Also the mail I am talking about is triggered by other users than the receiver and those users might reach the server via a base URL which I don't want to expose to the receiver of the mail. So I think setting up something like a "main" or "official" base URL in "appSettings" is the best and easiest place.
Slauma