ContentRootPath
I have changed the ContentRootPath
to c:\images
as follows.
public class Program
{
// others are removed for simplicity.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseContentRoot(@"c:\images")
.UseStartup<Startup>();
}
There are only JPEG photos in c:\images
.
Controller
Using DI, I can access ContentRootPath
via _env
as follows.
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
string crp = _env.ContentRootPath;
object[] filepaths = Directory.GetFiles(crp)
.Select(x=>Path.GetFileName(x))
.ToArray<string>();
return View(filepaths);
}
[HttpGet]
public FileStreamResult ViewImage(string filename)
{
string filepath = Path.Combine(_env.ContentRootPath, filename);
byte[] data = System.IO.File.ReadAllBytes(filepath);
Stream stream = new MemoryStream(data);
return new FileStreamResult(stream, "image/jpeg");
}
}
CSHTML
@model IList<object>
@foreach (var item in Model)
{
<img src="/Home/ViewImage/@item" />
}
Problem and Question
filename
is always null
. What is wrong and how to fix it?