内容根路径
我已将其更改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>();
}
中只有 JPEG 照片c:\images。
控制器
使用 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。出了什么问题以及如何解决?