从 ASP.Net Core 的 wwwroot/images 获取图像。
ASP.Net Core 2.2版本中,出现了一个问题:如何从wwwroot/images目录中获取图片。解决方法是使用依赖注入在控制器中注入IHostingEnvironment接口的实例,并使用该实例来访问WebRootPath(wwwroot)。
具体解决方法如下所示:
在控制器中使用依赖注入:
[Route("api/[controller]")] public class GalleryController : Controller { private readonly IHostingEnvironment _hostingEnvironment; public GalleryController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } // GET api//5 [HttpGet("{id}")] public IActionResult Get(int id) { var path = Path.Combine(_hostingEnvironment.WebRootPath, "images", $"{id}.jpg"); var imageFileStream = System.IO.File.OpenRead(path); return File(imageFileStream, "image/jpeg"); } }
在控制器中注入了IHostingEnvironment接口的实例_hostingEnvironment,并使用它来访问WebRootPath(wwwroot)。在Get方法中,将图片的路径拼接为wwwroot/images/{id}.jpg,并打开该路径对应的图片文件流。最后,返回该图片文件流和"image/jpeg"作为文件类型给客户端。
这样,就可以在ASP.Net Core 2.2中通过依赖注入的方式,从wwwroot/images目录中获取图片了。
ASP.Net Core中从wwwroot/images获取图像的问题出现的原因是需要访问wwwroot/images文件夹中的图像文件,但没有直接的方法来获取图像的物理路径。为了解决这个问题,可以注入一个IHostingEnvironment接口,并使用其WebRootPath或WebRootFileProvider属性来获取图像的物理路径。
在控制器中,可以使用以下代码来注入IHostingEnvironment并获取图像的物理路径:
private readonly IHostingEnvironment env; public HomeController(IHostingEnvironment env) { this.env = env; } public IActionResult About(Guid foo) { var path = env.WebRootFileProvider.GetFileInfo("images/foo.png")?.PhysicalPath; }
在视图中,通常使用"Url.Content("images/foo.png")"来获取特定文件的URL。然而,如果出于某种原因需要访问物理路径,则可以按照相同的方法进行操作:
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment env
@{
var path = env.WebRootFileProvider.GetFileInfo("images/foo.png")?.PhysicalPath;
}
注意,在最新的.NET版本中,IHostingEnvironment已被弃用,并被IWebHostEnvironment取代,但是这里的代码看起来和使用方式是相同的,效果也是一样的 🙂
从wwwroot/images中获取图像是ASP.Net Core中常见的需求之一。然而,在ASP.Net Core 3和Net 5中,获取图像的方式有所不同。
在ASP.Net Core 3和Net 5中,可以通过以下代码来获取图像:
private readonly IWebHostEnvironment _env; public HomeController(IWebHostEnvironment env) { _env = env; } public IActionResult About() { var path = _env.WebRootPath; }
这段代码中,首先需要注入IWebHostEnvironment接口,并在构造函数中进行依赖注入。然后,在About方法中,可以通过_env.WebRootPath属性来获取wwwroot文件夹的路径。
这样,就可以通过拼接路径的方式来获取wwwroot/images文件夹中的图像了。
总结起来,ASP.Net Core 3和Net 5中获取wwwroot/images文件夹中的图像的方法是通过注入IWebHostEnvironment接口,并使用其WebRootPath属性来获取wwwroot文件夹的路径,然后拼接路径来获取图像。