Ult*_*ery -1 c# asp.net model-view-controller asp.net-mvc routes
目前我有 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>
Run Code Online (Sandbox Code Playgroud)
控制器
public ActionResult Trees(string id)
{
string path = Server.MapPath(String.Format("~/folder1/folder2/{0}", id));
string mime = MimeMapping.GetMimeMapping(path);
return File(path, mime);
}
Run Code Online (Sandbox Code Playgroud)
路由配置文件
routes.MapRoute(
name: "testing",
url: "Test/{filename}",
defaults: new { controller = "Park", action = "Trees", filename = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?我已经检查了这些类似的问题ASP.NET MVC 路由问题 如何摆脱ASP.NET MVC 路由中的问号?但这些解决方案都没有帮助我,也许是因为我有一个 @Url.Action 和 new { id = "name.pdf" } 这可能是不同的,因为这些问题都没有。
任何建议表示赞赏。谢谢。
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 }
);
}
Run Code Online (Sandbox Code Playgroud)
webconfig:将参数添加runAllManagedModulesForAllRequests="true"到模块节点。
<system.webserver>
<modules runAllManagedModulesForAllRequests="true">
...
</modules>
</system.webserver>
Run Code Online (Sandbox Code Playgroud)
cshtml:
<a class="dropdown-item" href="@Url.Action("Trees", "Park", new { @filename = "name.pdf" })" target="_blank">Text</a>
Run Code Online (Sandbox Code Playgroud)
控制器:
public ActionResult Trees(string filename)
{
string path = Server.MapPath(String.Format("~/folder1/folder2/{0}", filename));
string mime = MimeMapping.GetMimeMapping(path);
return File(path, mime);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
747 次 |
| 最近记录: |