![](/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.