Friday, June 3, 2011

MVC - Using Views outside of /Views or other content in /Views

I learned something new recently regarding this subject.
First - to use a View outside of the /Views folder you must put a copy of your web.config from /Views into your new folder. It's that simple.

Secondly - Views by default won't allow other content in them. If you drop a css file in the /Views folder and reference it via http://localhost/views/test.css you will get a 404 file not found error.

If we look in the web.config inside of our views, we have:

      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>

This essentially says make any item referenced in /Views (from path="*") a 404 status code - hence file not found. This means you can't address css files, jpegs, etc. - anything inside of /Views.
The workaround is easy though. Simply change the defined handler to exclude ONLY *.cshtml (hence views)

Ideally we probably want to exclude *.cshtml and *.aspx in case we have any web forms view engine code. Unfortunately IIS6 and IIS7 have different syntax here. Changing the web.config in the /Views folder we have:

      <add path="*.cshtml,*.aspx" verb="*" type="System.Web.HttpNotFoundHandler" />

In IIS7:
      <add name="ExcludeRazorViews" path="*.cshtml" verb="*" type="System.Web.HttpNotFoundHandler" />
      <add name="ExcludeWebFormsViews" path="*.aspx" verb="*" type="System.Web.HttpNotFoundHandler" />

Note also that the web.config in the /Views folder also contains this one as well at the bottom you'll need to watch out for that is provided for IIS 7 compatibility:
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />


  1. 1- Make new folder in Views, eg. myFolder
    2- Add your static page, eg. filename.cshtml
    3- Copy the web.config file from "Views" folder and paste it to the new folder you just created inside Views (eg. myFolder)
    4- In the pasted web.config Replace
    this :

    with this :

    Resault :
    Any file in this folder will work without routing!

    Freedom to Palestine, from palestinian programmer

    1. it depends on your version of iis, note the difference settings above