MVC 通配符路由映射不适用于文档
本文关键字:适用于 文档 不适用 映射 通配符 路由 MVC | 更新日期: 2023-09-27 18:32:10
我的 MVC 站点中有一个页面,用于浏览服务器上的文件夹结构,但通配符映射不适用于文档。
映射适用于文件夹名称,例如
http://localhost:4321/Document/Folder/General_HR
哪个映射到共享云端硬盘文件夹,例如控制器中的T:'root'General_HR
。
但是我得到一个 404,并且在尝试访问
诸如http://localhost:4321/Document/Folder/General_HR/Fire_Drill_Procedures.doc
这是路由映射
routes.MapRoute("Document Folder",
"Document/Folder/{*folderPath}",
new { controller = "Document", action = "Folder" });
我也有在上述路由之后应用的标准 MVC 路由:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
我尝试注释掉所有其他路线,但它仍然不起作用。
我曾经让它工作过,但我不知道从那以后发生了什么变化。它似乎正在寻找位于C:'MyProject'General_HR
的资源,而不是路由到控制器。如何修复我的映射以解决此问题?根据这个答案,它应该可以工作。
我的控制器方法的工作原理是这样的:如果URL参数包含扩展名,那么我return File(filePath)
,否则我创建一个视图模型并返回View(viewModel)
。因此,当我单击带有扩展名的内容时,它仍然应该指向相同的控制器方法并返回文件。
public virtual ActionResult Folder(string folderPath)
{
var actualFolderPath = folderPath;
if (string.IsNullOrEmpty(actualFolderPath))
{
actualFolderPath = DocumentPathHelper.RootFolder;
}
else
{
actualFolderPath = DocumentPathHelper.GetActualFileLocation(actualFolderPath);
}
if (System.IO.File.Exists(actualFolderPath))
{
return File(actualFolderPath, MimeMapping.GetMimeMapping(actualFolderPath));
}
var vm = new FolderViewModel();
//build vm
return View(vm);
}
我通过将
.
替换为占位符,然后将其替换回控制器来更改文档的 URL 来"解决"这个问题。
对于每个项目:
folderPath = folderPath.Replace(".", "___");
然后在控制器中:
public virtual ActionResult Folder(string folderPath)
{
var actualFolderPath = folderPath.Replace("___", ".");