![](/img/trans.png)
[英]Visual Studio 2017 does not create a new empty MVC controller in ASP.NET Core MVC project
[英]How to create a symbolic link to images in Visual Studio 2017 with ASP.NET Core project?
我有一个在 ASP.NET Core 2.2 框架之上使用C#
编写的项目。
我的项目外的文件夹中有资产图像,我需要让外部世界可以访问这些图像。 我的图片实际位于c:/public_assets/photos
。 当我的应用程序运行 URI https://mydomain/public/any_image.jpg
,需要显示在c:/public_assets/photos/any_image.jpg
找到的图像。
然后我会像这样使用剃刀视图渲染我的图片
<img src="~/public/any_image.jpg" alt="..." />
我希望这将是添加到项目配置文件的设置,因此当我将项目部署到生产时,我只需更改配置。
您需要将静态文件添加到您的应用构建器。 “ 在Web根目录之外服务文件”部分提供了有关如何执行此操作的详细说明。
在您的情况下,导航到您的Startup
类。 在public void Configure(IApplicationBuilder app ....)
添加以下代码
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(@"c:/public_assets/photos"),
RequestPath = "/photos"
});
现在,您应该可以使用如下视图渲染照片了
<img src="~/public/any_image.jpg" alt="..." />
添加一个新的控制器
public class publicController : Controller
{
public FileResult pic(string id)
{
var fileName = id;
if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) throw new Exception();
string absolutePath = Path.GetFullPath(Path.Combine("c:/public_assets/photos/", fileName));
if (!System.IO.File.Exists(absolutePath)) throw new Exception();
byte[] fileBytes = System.IO.File.ReadAllBytes(absolutePath);
string fileExtension = Path.GetExtension(absolutePath).Replace(".", "");
fileName = Path.GetFileName(absolutePath);
return File(fileBytes, "image/" + fileExtension, fileName);
}
}
编辑
检查所有文件扩展名
public class publicController : Controller { public ActionResult pic(string id) { var fileName = id; if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) return NotFound(); string absolutePath = Path.GetFullPath(Path.Combine("c:/public_assets/photos/", fileName)); if (!System.IO.File.Exists(absolutePath)) return NotFound(); string fileExtension = Path.GetExtension(absolutePath).Replace(".", "").ToLower(); if (fileExtension != "jpg") return NotFound(); var fileBytes = System.IO.File.OpenRead(absolutePath); fileName = Path.GetFileName(absolutePath); return File(fileBytes, "image/" + fileExtension, fileName); } }
然后打电话
http://xxxxxxxxx/public/pic/1.jpg
http://xxxxxxxxx/public/pic/MikeA.jpg
使用FileServer
扩展方法,将当前代码添加到Startup.cs
Configuration
方法中:
public class Startup {
public void Configure(IApplicationBuilder app) {
// other configure code
var opts = new FileServerOptions {
RequestPath = "/public",
FileProvider = new PhysicalFileProvider(@"c:/public_assets/photos")
};
app.UseFileServer(opts);
}
}
然后,您可以在剃须刀页面中使用如下图像网址:
<img src="~/public/any_image.jpg" alt="..." />
您还可以将两个路径字符串放入appSettings.json
,并从配置中读取它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.