Pablo Santa Cruz Pablo Santa Cruz - 2 months ago 9
ASP.NET (C#) Question

Using images on Web Applications and Visual Studio for ASP.NET MVC

I am developing an ASP.NET MVC applications with MS Visual Studio 2008 SP1.

My project structure is the default one:


Project |-Content |-css |-img |-Models |-Views
|-Controllers


The thing is, I am able to access all the content placed under Content directory provided the file is included in the project. On the other hand, if I happen to have an image (I.E. an image uploaded by the user) that's on the right physical directory (Project\Content\img) but is not included in the project, I keep getting a 404 error when I access them with a browser.

I think my URL is correct:

http://localhost:1260/Content/img/my_image.jpg

And I do have a file under Project\Content\img\my_image.jpg.

What can be wrong? Am I forced to include all the files on the project? I don't think so, because that would mean that I can't have images uploaded and saved by the web users this way.

Thanks a lot.

Answer

If you're hosting your project with IIS 7, you must add he content-type in IIS 7(Handler Mapping). But if you're hosting your project with the Asp.net Developer Server, it's not required.

Using the following code in web.config file

<configuration>
   <system.webServer>
     <handlers>
      <add name="css mapping" path="*.css" verb="*" type="System.Web.StaticFileHandler" resourceType="Unspecified" preCondition="integratedMode" />
      <add name="js mapping" path="*.js" verb="*" type="System.Web.StaticFileHandler" resourceType="Unspecified" preCondition="integratedMode" />
      <add name="gif mapping" path="*.gif" verb="*" type="System.Web.StaticFileHandler" resourceType="Unspecified" preCondition="integratedMode" />
      <add name="jpg mapping" path="*.jpg" verb="*" type="System.Web.StaticFileHandler" resourceType="Unspecified" preCondition="integratedMode" />
      <add name="png mapping" path="*.png" verb="*" type="System.Web.StaticFileHandler" resourceType="Unspecified" preCondition="integratedMode" />      
     </handlers>
   </system.webServer>
</configuration>