c# - 如何在 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,这可能是不同的,因为这些问题都没有。
任何建议表示赞赏。谢谢。
解决方案
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);
}
推荐阅读
- python - 当去 http://localhost@admin 时,它会显示 python 的实际脚本
- java - 类加载器:委托层次结构算法
- docker - 如何通过 LLVM build_docker_image.sh 默认使用 libc++ 构建 clang?
- r - 格兰奇 - (左)加入
- python - 尝试将 y 变量读入 pyplot.scatter 时出现 IndexError
- android - 是否可以存档当前的商品列表重新上传 apk 到新的商品列表
- csv - Spark:没有输入文件名
- arrays - 将下采样图像映射到原始分辨率 - MATLAB
- sql-server - 限制每组中只有一个标记为主要的记录
- javascript - Jquery兄弟姐妹在警报中显示未定义