要在ASP.NET Core中枚举目录文件并进行IIS托管,你可以按照以下步骤进行操作:
创建一个ASP.NET Core Web应用程序项目。
在Startup.cs文件中,添加所需的命名空间:
using System.IO;
using Microsoft.Extensions.FileProviders;
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseStaticFiles();
// ...
}
using Microsoft.AspNetCore.Mvc;
public class FileSystemController : Controller
{
private readonly IWebHostEnvironment _environment;
public FileSystemController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult Index(string directory = "")
{
var path = Path.Combine(_environment.WebRootPath, directory);
var fileProvider = new PhysicalFileProvider(path);
var contents = fileProvider.GetDirectoryContents("");
return View(contents);
}
}
@model IEnumerable
Files and Directories
@foreach (var item in Model)
{
-
@if (item.IsDirectory)
{
var directory = string.IsNullOrEmpty(Model.FirstOrDefault()?.PhysicalPath) ? item.Name : Path.Combine(Model.FirstOrDefault()?.PhysicalPath, item.Name);
@item.Name
}
else
{
@item.Name
}
}
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "fileSystem",
pattern: "FileSystem/{**directory}",
defaults: new { controller = "FileSystem", action = "Index" });
});
http://localhost:port/FileSystem
以浏览文件和目录。这样,你就可以在ASP.NET Core中枚举目录文件并进行IIS托管了。