How to create a fully qualified hyperlink to a resource dynamically?
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)
S开发者_JAVA百科o 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!
Something like this:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath.TrimEnd('/')
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
What about to place it into the web.config
<configuration>
<appSettings>
<add key="SendingUrlBase" value="http://www.BlaBla.com"/>
精彩评论