Search code examples
asp.netasp.net-mvc-3iisrelative-pathvirtual-directory

How to detect if the web application is deployed as a virtual directory?


My MVC3 Web Application is not always deployed as a site in IIS, so I need to detect if it has been deployed as a virtual directory or application in order to handle the path string.

for example, if the site is deployed as a website under IIS root, if i write:

\ABC\test.txt

this is fine, the request goes to http://somehost/ABC/test.txt

but if the site is deployed as a virtual directory or application under an existing site in IIS, for example:

http://somehost/mymvcapp/

then, the request for "\ABC\test.txt" will not be correct.

I understand that write "~\App_Data\test.txt" will solve the problem, but "~\" can only be processed by the server in current web context. Sometime I need to do some process on the file in other layers, they can't touch web context.

So I need to detect if the application has been deployed as a virtual directory. and find the actual physical path to the file. Is there any way to do it?


Solution

  • If your business layer can't reference System.Web, then you have to expect that it can't detect any information about your web application period. This means that the code should not be expected to resolve file paths within your site.

    What you could do instead is have an intermediate configuration layer that the application initializes and the business layer can consume. For example, given this interface which is accessible to both layers:

    public interface IConfiguration
    {
        string DataFolder { get; }
    }
    

    ... you could have code in your Global.asax that initializes it:

    IConfiguration config = ...;
    ...
    config.DataFolder = this.Server.MapPath("~/App_Data");
    

    Your business layer can now just read the configuration and form a path to the expected file:

    var filePath = Path.Combine(this.configuration.DataFolder, "test.txt");