If I have a relative path that I need to get from the current server. The following does not work because it is not a valid URI.
var request = WebRequest.Create("\path_to_resource")
I believe that the easiest way would be to put the path in the web.config, however this is easily broken by forgetting to update the config when the application 开发者_Go百科is moved to another server. Is there a better way than?
var request = WebRequest.Create(ConfigurationManager.AppSettings["root"] + "\path_to_resource");
Well, you can always use something like:
private string CurrentDomain()
{
string currDomain = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host;
if (Request.Url.Port != 80 && Request.Url.Port != 443)
currDomain += (":" + Request.Url.Port);
return currDomain;
}
Using these various Request object properties will give you your current domain name onto which you can append your sub-folders for your resource.
Request.Url.Scheme
is the http / https
part of the URL, System.Uri.SchemeDelimiter
is the ://
part, and the Request.Url.Host
will be your actual host name (ie. example.com
).
If your site is running on a non-standard port, the calls to Request.Url.Port
will add that into the URL "domain name" also.
Note that this is not bullet-proof code, as it assumes your (for example) running SSL (https) on the default port of 443
If you need actual physical file paths, you can use Server.MapPath to retrieve the physical file path of the "root" of your ASP.NET application, and append your sub-folders from there.
See also: ASP.NET Web Site Paths
精彩评论