【问题标题】:MVC Wild Card route mapping not working on documentsMVC 通配符路由映射不适用于文档
【发布时间】:2023-03-19 17:20:02
【问题描述】:

我的 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 的资源,而不是被路由到控制器。如何修复我的映射以解决此问题?根据this answer,它应该可以工作。

我的控制器方法是这样工作的:如果 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,即 *.doc 不会发送到 MVC 路由框架,而是尝试由 IIS 直接提供服务。有关解决方法,请参阅这篇文章:weblogs.asp.net/jongalloway/…。它适用于通过 MVC 路由框架提供 *.html,但您可以对任何文件扩展名遵循相同的过程。

标签: c# asp.net-mvc routing asp.net-mvc-routing


【解决方案1】:

我通过将 . 替换为占位符,然后将其替换回控制器中来更改文档的 URL,从而“解决”了这个问题。

对于每个项目:

folderPath = folderPath.Replace(".", "___");

然后在控制器中:

    public virtual ActionResult Folder(string folderPath)
    {
        var actualFolderPath = folderPath.Replace("___", ".");

【讨论】:

    猜你喜欢
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多