Images that are in App_Data folder not shown in browser

Viewed 27860

When I set image URL property to asp image control that is in App_Data folder, image is showing in page design view but not in browser.

<form id="form1" runat="server">
<div>
    <asp:Image ID="Image1" runat="server" ImageUrl="~/App_Data/p3.jpg" />
</div>
</form>

It seems to be straightforward, but it's not showing the image.

8 Answers
public string ReturnImage(){
 
alternatively if you wanted to pass a param.

so for example

int WhatEverId = 5;

String folderPath = string.empty;
HostingEnvironment.MapPath("~/App_Data/YourFolder") + @"\" +WhatEverId.ToString());

 string imageYouWantToDisplay = "Test.png";
 string base64String = "";
 String path = HostingEnvironment.MapPath("~/App_Data");
 
 using (Image image = Image.FromFile(path + "/" + imageYouWantToDisplay))
  {
     using (MemoryStream m = new MemoryStream())
      {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
          base64String = Convert.ToBase64String(imageBytes);
      }
    }

    return base64String;

}

you can then call that in an action method

public DisplayImages (){
List<WhateverModel> test = new List<WhateverModel>();

 test = GetAll().ToList();

  test.ForEach(x=> { MyImage = ReturnImage();});

  return test;

  }

View

@model WhateverModel
<img src="@MyImage" /> or in js  <img src="${MyImage}" />

If you use the IIS Administration tool and go to Content Filtering (for your application), there is a Hidden Segments tab where you can remove App_Data

You'll notice this adds to Web.Config inside the "<system.webServer>" node:

<security>
    <requestFiltering>
        <hiddenSegments>
            <remove segment="App_Data" /> 
        </hiddenSegments>
    </requestFiltering>
</security>

A valid reason for doing that is if you use WebDeploy Publishing and want an easy way to set it to remove additional files at destination, excluding files from the App_Data folder (assuming you're not publishing anything from your project into App_Data and don't keep anything private there at the server side).

enter image description here

Configuring WebDeploy to not delete other specific folder when using the UI client seems to be problematic at least (see How to skip delete on folder during publish?)

Related