Reputation: 452
I have a database and a dbinitializer class that populated the database with test data. one of my columns of one of my tables are for storing a string path to images. ie: Image="~/Content/Images/example.img"
then my view model is supposed to render the image for each item in the table.
@foreach (var item in Model) {
<img style="width:200px;height:250px;" src="@Url.Content(item.Image)" alt="@item.Name" />
}
This exact method works in my normal mvc app but when i tried to emulate the exact same code in my core app the images arent rendering. Does anyone know why I could be getting this problem?
Upvotes: 1
Views: 1873
Reputation: 218872
In ASP.NET core, static files are served from only the wwwroot
folder by default. That means if you try to access a file from Contents/Images, which is your root, it won't work.
The good news is, You can configure the static file location as you wish. So update your Configure
method in startup.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// Your existing code goes here
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"Content/Images")),
RequestPath = new PathString("/Images")
});
}
Now these images can be accessed from the browser like this yourSiteName/Images/imageFile.png
Now you can fix your view code to get image from this path.
@foreach (var item in Model)
{
<div>
<img src="@Url.Content("~/Images/"+item.Image)" />
</div>
}
Assuming item.Image
value for each item in the collection has some value like this MyImage.png
and you have an image called MyImage.png
located at the Contents/Images
which is in your application root (not in the wwwroot directory
)
You may also consider moving the images to the wwwroot directory because the ASP.NET team added that directory for purposes like this ( static assets).
Upvotes: 2