Search code examples
c#asp.neturliis-6virtual-directory

How do I resolve absolute URLs for different sites in the same parent IIS virtual directory in .NET?


My goal is to share images, css, js, etc. across multiple websites that are all hosted under the same parent virtual directory in IIS. Of course, I could hard code the images paths, but I'd hoped .NET had a method that could intelligently resolve URLs using the IIS configuration.

Here is my file/virtual directory structure:

Parent Site (Virtual Directory)
  default.aspx
  mypage.aspx
  otherpage.aspx
  images
    - logo.jpg
  css
    - site.css
  Subsite1 (Virtual Directory)
    - default.aspx
    - products.aspx
  Subsite2 (Virtual Directory)
    - default.aspx
    - products.aspx
    - miscellaneous.aspx

Parent Site, Subsite1, and Subsite2 are all virtual directories set up for http://parentsite.com, http://subsite1.com, and http://subsite2.com, respectively. I want to share images, js, css, etc. across these sites.

Is there a method in .NET that will resolve ~/images/logo.jpg as http://parentsite.com/images/logo.jpg when called from one of the subsites (e.g., http://subsite.com/default.aspx)?


Solution

  • In IIS6 and even IIS7 you can use a new virtual directory, call it "assets", in all of the children sites.

    Updated site layout:

    Parent Site (Virtual Directory)
         default.aspx
         mypage.aspx
         otherpage.aspx
         assets
              -images
                   - logo.jpg
              -css
                   - site.css    
    
    Subsite1 (Virtual Directory)
         - default.aspx
         - products.aspx
         assets (Virtual Directory to parent assets)
    
    Subsite2 (Virtual Directory)
         - default.aspx
         - products.aspx
         - miscellaneous.aspx 
         assets (Virtual Directory to parent assets)
    

    With this structure you can share the same "assets" folder with all sites and still access it as "~/assets". This allows you to use the assets with any of the domains that IIS is answering for.

    http://parentsite.com/assets

    http://childsite.com/assets

    A CDN is a good option but often times you would create seperate DNS enteries for each site like http://cdn.parentsite.com and http://cdn.childsite.com and then create some function to reference the files as http://cdn.(currentdomain).

    In my opinion, using an absolute or relative path to the shared assets folder will make life easier for you.