How can I request a resource (relative path) from the current server?

If I have a relative path that I need to get from the current server. The following don't work because it is not a valid URI.

var request = WebRequest.Create("\path_to_resource")

      

I believe the easiest way would be to set the path in the web.config, however this is easy to break by forgetting to update the config when the app is moved to another server. Is there a better way than that?

var request = WebRequest.Create(ConfigurationManager.AppSettings["root"] + "\path_to_resource");

      

+2


source to share


1 answer


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 properties , you will get your current domain name to which you can add your subfolders for your resource.



Request.Url.Scheme

is part of the http / https

url, System.Uri.SchemeDelimiter

is part of ://

, and Request.Url.Host

will be your actual hostname (i.e. example.com

).
If your site is running on a non-standard port, calls to Request.Url.Port

will also add it to the "domain name" URL.
Note that this is not bulletproof code as it assumes your (for example) is running SSL (https) on the default port 443

If you want the actual physical file paths, you can use Server.MapPath to get the physical path to your ASP.NET "root" file and add your subfolders there.

See also: ASP.NET Website Paths

+3


source







All Articles