ContentRootPath
Я изменил значение ContentRootPath
на c:\images
следующим образом.
public class Program
{
// others are removed for simplicity.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseContentRoot(@"c:\images")
.UseStartup<Startup>();
}
В контроллере c:\images
.
имеются только фотографии JPEG.
Используя DI, я могу получить доступ к ContentRootPath
через _env
следующим образом.
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" />
}
Проблема и вопрос
filename
всегда null
.Что не так и как это исправить?