首页 > 解决方案 > 如何在 URL MVC 路由上从问号 (?) 更改为斜线 (/)?

问题描述

目前我有正确显示在页面上的 pdf 文件,但 URL 显示为“/Test?id=name.pdf”,我希望它显示为“/Test/name.pdf”。我怎样才能做到这一点?

这是我的代码:

.cshtml

<a class="dropdown-item" href="@Url.Action("Trees", "Park", new { id = "name.pdf" })" target="_blank">Text</a>

控制器

public ActionResult Trees(string id)
{
    string path = Server.MapPath(String.Format("~/folder1/folder2/{0}", id));

    string mime = MimeMapping.GetMimeMapping(path);

    return File(path, mime);
}

路由配置.cs

    routes.MapRoute(
        name: "testing",
        url: "Test/{filename}",
        defaults: new { controller = "Park", action = "Trees", filename  = UrlParameter.Optional }
    );

知道我做错了什么吗?我已经检查了这些类似的问题ASP.NET MVC Routing question 如何摆脱 ASP.NET MVC 路由中的问号?但是这些解决方案都没有帮助我,也许是因为我有一个带有 new { id = "name.pdf" } 的@Url.Action,这可能是不同的,因为这些问题都没有。

任何建议表示赞赏。谢谢。

标签: c#asp.netasp.net-mvcmodel-view-controllerroutes

解决方案


Test/{filename}因此,您的路由 url 参数filename应该替换id您的 cshtml 和控制器中的参数。

编辑:您需要将您的路由添加到默认路由之上,并向 webconfig 模块添加一个参数。我们还需要编辑 webconfig,因为默认情况下它们不支持该.符号。

编辑 2:不要忘记将目录或文件添加到 Visual Studio 解决方案。

routeconfig.cs:在默认路由之前添加路由。

public static void RegisterRoutes(RouteCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

   routes.MapRoute(
      name: "testing",
      url: "Test/{filename}",
      defaults: new { controller = "Park", action = "Trees", filename = UrlParameter.Optional }
   );

   routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );
}

webconfig:将参数添加runAllManagedModulesForAllRequests="true"到模块节点。

<system.webserver>
   <modules runAllManagedModulesForAllRequests="true">
      ...
   </modules>
</system.webserver>

cshtml:

<a class="dropdown-item" href="@Url.Action("Trees", "Park", new { @filename = "name.pdf" })" target="_blank">Text</a>

控制器:

public ActionResult Trees(string filename)
{
    string path = Server.MapPath(String.Format("~/folder1/folder2/{0}", filename));

    string mime = MimeMapping.GetMimeMapping(path);

    return File(path, mime);
}

推荐阅读