ASP.NET MVC - Using content in /Views folderhttp://forums.asp.net/t/1689087.aspx/1?ASP+NET+MVC+Using+content+in+Views+folderSun, 12 Jun 2011 21:52:16 -040016890874456632http://forums.asp.net/p/1689087/4456632.aspx/1?ASP+NET+MVC+Using+content+in+Views+folderASP.NET MVC - Using content in /Views folder <p>Hello community,</p> <p>Today I want show you some trick that I learned by investigating some problem some time ago.<br> <br> For example, you want to include some content (.js, .css, .jpg etc) to your website from folder /Views.<br> The reasons for this scenario could be different. Maybe such architecture, maybe customers wants this.<br> It does not matter. In this case we have some problem.<br> <br> E.g. we want to include style sheet from /Views folder:</p> <pre class="prettyprint">&lt;link href=&quot;/Views/test.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;</pre> <p>When we open this in browser we will get an error 404 (Not Found).<br /><br />The reason for this behavior lies in web.config file in the folder /Views<br />If we open this file we can noticed next string:</p> <pre class="prettyprint">&lt;httpHandlers&gt; &lt;add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/&gt; &lt;/httpHandlers&gt;</pre> <p>So all requests that starts from /Views will be redirected to HttpNotFoundHandler handler and we will see appropriate error.<br /><br />If we remove this string then we can access to our content.<br />But potential attacker can open direct link to our view-files, e.g: http://localhost/Views/Home/Index.aspx<br /><br />So we can protect from displaying only this files (.aspx and .cshtml)<br /><br />To do this we should configure web.config file in folder /Views:</p> <pre class="prettyprint">&lt;system.web&gt; &lt;httpHandlers&gt; &lt;add path="*.cshtml" verb="*" type="System.Web.HttpNotFoundHandler" /&gt; &lt;add path="*.aspx" verb="*" type="System.Web.HttpNotFoundHandler" /&gt; &lt;/httpHandlers&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;handlers&gt; &lt;add name="DontShowCsHtml" path="*.cshtml" verb="*" type="System.Web.HttpNotFoundHandler" /&gt; &lt;add name="DontShwAspx" path="*.aspx" verb="*" type="System.Web.HttpNotFoundHandler" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt;</pre> <p>And now our views are protected from displaying and we can access to necessary content in folder /Views.<br> <br> Hope this will help someone quickly deal with similar problem, while others could learn for yourself something new.</p> <p></p> 2011-06-12T21:52:16-04:00