求助:基于ASP.NET Core开发简易文件浏览Web应用的功能实现
解决方案步骤
1. 修复路由问题(解决深层级目录失效)
之前的参数方案仅能捕获单个层级路径,改用通配符路由捕获任意层级的路径:
在Program.cs中配置控制器路由:
app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{*path}");
这里的{*path}会捕获URL中/Index/之后的所有内容,比如/windows/system32会被解析为path = "windows/system32"。
2. 实现文件夹导航与HTML文件自动展示逻辑
在HomeController的Index方法中,处理路径映射、安全校验及核心业务逻辑:
using System.IO; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.StaticFiles; public class HomeController : Controller { public IActionResult Index(string path = "") { // 定义服务器上的根目录(根据你的实际需求修改) string rootDir = @"C:\"; // 拼接当前请求的完整路径 string currentPath = Path.Combine(rootDir, path ?? ""); // 安全校验:防止路径遍历攻击,确保请求路径在根目录范围内 string fullCurrentPath = Path.GetFullPath(currentPath); if (!fullCurrentPath.StartsWith(Path.GetFullPath(rootDir), StringComparison.OrdinalIgnoreCase)) { return Forbid(); // 非法路径,拒绝访问 } if (Directory.Exists(fullCurrentPath)) { // 检测当前目录下的HTML文件 var htmlFiles = Directory.GetFiles(fullCurrentPath, "*.html", SearchOption.TopDirectoryOnly); if (htmlFiles.Length == 1) { // 存在单个HTML文件,直接返回该文件内容让浏览器渲染 return PhysicalFile(htmlFiles[0], "text/html"); } // 获取当前目录下的子文件夹和文件 var directories = Directory.GetDirectories(fullCurrentPath) .Select(dir => new { Name = Path.GetFileName(dir), Path = GetRelativePath(rootDir, dir) }); var files = Directory.GetFiles(fullCurrentPath) .Select(file => new { Name = Path.GetFileName(file), Path = GetRelativePath(rootDir, file) }); // 传递数据到视图 ViewBag.Directories = directories; ViewBag.Files = files; ViewBag.CurrentPath = path; return View(); } else if (File.Exists(fullCurrentPath)) { // 是文件,返回下载(你已实现的功能) var provider = new FileExtensionContentTypeProvider(); if (!provider.TryGetContentType(fullCurrentPath, out string contentType)) { contentType = "application/octet-stream"; } return PhysicalFile(fullCurrentPath, contentType, Path.GetFileName(fullCurrentPath)); } return NotFound(); } // 辅助方法:获取相对于根目录的路径(用于生成页面链接) private string GetRelativePath(string rootDir, string fullPath) { return Path.GetRelativePath(rootDir, fullPath).Replace(Path.DirectorySeparatorChar, '/'); } }
注意:需要安装Microsoft.AspNetCore.StaticFiles NuGet包来获取正确的文件MIME类型。
3. 编写视图(Index.cshtml)
模仿浏览器目录样式,展示文件夹、文件及上级目录链接:
@{ ViewData["Title"] = "Directory Listing"; } <h1>@(string.IsNullOrEmpty(ViewBag.CurrentPath) ? "Root Directory" : ViewBag.CurrentPath)</h1> @if (!string.IsNullOrEmpty(ViewBag.CurrentPath)) { <!-- 返回上级目录的链接 --> <p><a href="@Url.Action("Index", new { path = Path.GetDirectoryName(ViewBag.CurrentPath)?.Replace(Path.DirectorySeparatorChar, '/') })">.. (Parent Directory)</a></p> } <h2>Folders</h2> <ul> @foreach (var dir in ViewBag.Directories) { <li><a href="@Url.Action("Index", new { path = dir.Path })">📁 @dir.Name</a></li> } </ul> <h2>Files</h2> <ul> @foreach (var file in ViewBag.Files) { <li><a href="@Url.Action("Index", new { path = file.Path })">📄 @file.Name</a></li> } </ul>
点击文件夹链接会进入对应目录加载内容,点击文件会触发下载,若目录存在单个HTML文件则直接渲染该页面。
4. 关键细节说明
- 文件夹导航:通过生成对应相对路径的链接,路由捕获完整路径后传递给Index方法,加载对应目录内容。
- HTML文件自动展示:检测到单个.html文件时,直接返回文件内容,浏览器自动渲染页面替代文件列表。
- 安全防护:通过
Path.GetFullPath和路径前缀校验,阻止恶意用户通过../等方式访问服务器敏感目录。
内容的提问来源于stack exchange,提问作者MrGlass33
相关产品推荐
相关产品推荐

