Asp.Net Mvc 5 image not displaying

风流意气都作罢 提交于 2021-02-07 20:02:19

问题


I have same images in Content and Views folders. I am trying to display images as below:

<img src="~/Content/Images/download.png" alt="Content folder" />
<br />
<br />
<img src="~/Views/Home/download.png" alt="Views folder" />
<br />

The image in Content folder displays successfully but the one in Views folder doesn't display and gives below error:

Failed to load resource: the server responded with a status of 404 (Not Found)

But actually, the resource is there. Here are my folders:

Could you please tell me which point I am doing wrong? I am using MVC 5 with razor engine and Visual Studio 2015 community edition.


回答1:


Unless you changed the default configuration, folder Views contains file Web.config that has settings for restricting access to files in this folder:

<system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" 
           type="System.Web.HttpNotFoundHandler" />
    </handlers>
</system.webServer>

So you can either remove this handler (which is not recommended for security purposes), or move your static files to some other folder, e.g. Content.




回答2:


Its because of the inbuilt security of ASP MVC to protect your views being accessed directly. Check removing 'BlockViewHandler' handler entry from ~/Views/web.config

My advice is to move image to 'Content' folder and keep 'Views' folder clean.




回答3:


Any MVC Version not allow to load other resource except html from Views folder. Because when you call a URL it waiting for text/html content type and because of that image inside main Views folder not able to render in page.

for better information please check file header request and response in browser (development tool/F12) network tab.

Response of image from Views:

Response of image from content folder:




回答4:


In .net core 3 you will also need this below line in startup.cs

app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = "/wwwroot/images"
            });


来源:https://stackoverflow.com/questions/39556570/asp-net-mvc-5-image-not-displaying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!