ASP.Net MVC 路由映射
-
08-06-2019 - |
题
我是 MVC(和 ASP.Net 路由)的新手。我正在尝试绘制地图 *.aspx
到一个名为 PageController
.
routes.MapRoute(
"Page",
"{name}.aspx",
new { controller = "Page", action = "Index", id = "" }
);
上面的代码不会将 *.aspx 映射到 PageController
?当我运行此命令并输入任何 .aspx 页面时,我收到以下错误:
找不到路径“/Page.aspx”的控制器,或者它没有实现 IController 接口。参数名称:控制器类型
有什么事情我没有在这里做吗?
解决方案
我刚刚回答了我自己的问题。我向后有路线(默认为页面上方)。
是的,您必须将所有自定义路由放在默认路由之上。
所以这就提出了下一个问题......“默认”路由如何匹配(我认为他们在此处使用正则表达式)“页面”路由?
默认路由匹配基于我们所说的约定优于配置。Scott Guthrie 在他关于 ASP.NET MVC 的第一篇博客文章中对此进行了很好的解释。我建议您通读它以及他的其他帖子。请记住,这些是基于第一个 CTP 发布的,并且框架已发生变化。您还可以在 asp.net 站点上找到 Scott Hanselman 编写的有关 ASP.NET MVC 的网络广播。
其他提示
我刚刚回答了我自己的问题。我有向后的路线(默认位于页面上方)。下面是正确的顺序。所以这就提出了下一个问题......“默认”路由如何匹配“页面”路由(我假设他们在这里使用正则表达式)?
routes.MapRoute(
"Page",
"{Name}.aspx",
new { controller = "Page", action = "Display", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
在 Rob Conery 的 MVC 店面之一上 截屏视频, ,他遇到了这个确切的问题。如果你有兴趣的话,大概在 23 分钟左右。
不确定您的控制器看起来如何,该错误似乎表明它无法找到控制器。创建 PageController 类后是否继承了 Controller ?PageController 是否位于 Controllers 目录中?
这是我在 Global.asax.cs 中的路线
routes.MapRoute(
"Page",
"{Page}.aspx",
new { controller = "Page", action = "Index", id = "" }
);
这是我的控制器,位于 Controllers 文件夹中:
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class PageController : Controller
{
public void Index()
{
Response.Write("Page.aspx content.");
}
}
}
public class AspxRouteConstraint : IRouteConstraint
{
#region IRouteConstraint Members
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return values["aspx"].ToString().EndsWith(".aspx");
}
#endregion
}
注册所有aspx的路由
routes.MapRoute("all",
"{*aspx}",//catch all url
new { Controller = "Page", Action = "index" },
new AspxRouteConstraint() //return true when the url is end with ".aspx"
);
您可以通过以下方式测试路线 MvcRoute可视化工具