Brian Brian - 1 month ago 15
ASP.NET (C#) Question

Asp.Net Absolute Path of a URL

To make it simpler for a webapp to share files with another app on a different server, I'm using a base href tag in my master page. As many people have discovered, this breaks webform paths. I have a working Form Adaptor class but am not sure how to get the absolute path of the url. Currently, my program is hardcoded to use something akin to :

HttpContext Context = HttpContext.Current;
value = "http://localhost" + Context.Request.RawUrl;


It is worth noting that I'm currently testing on my local IIS server, so there's a strange tendency for a lot of things I've tried using in order what the absolute path do not include the domain name (my local IIS is not visible externally). Which means it isn't an absolute path and thus the base href will wreck it.

Is there a good way to handle this such that it will work locally without hardcoding but will also work properly when uploaded to a server? I'd prefer to avoid anything that involves doing something different on the server-side copy.

Yes, I realize I could use separate web.config files locally and on the server to get this information but this is ugly and violates DRY.

Answer

I have used this in the past:

// Gets the base url in the following format: 
// "http(s)://domain(:port)/AppPath"
HttpContext.Current.Request.Url.Scheme 
    + "://"
    + HttpContext.Current.Request.Url.Authority 
    + HttpContext.Current.Request.ApplicationPath;
Comments