ASP.Net MVC路由映射

时间:2020-03-05 18:39:49  来源:igfitidea点击:

我是MVC(和ASP.Net路由)的新手。我正在尝试将* .aspx映射到名为PageController的控制器。

routes.MapRoute(
   "Page",
   "{name}.aspx",
   new { controller = "Page", action = "Index", id = "" }
);

上面的代码不会将* .aspx映射到PageController吗?当我运行此命令并键入任何.aspx页时,出现以下错误:

The controller for path '/Page.aspx' could not be found or it does not implement the IController interface.
  Parameter name: controllerType

我这里有没有做的事吗?

解决方案

回答

不确定控制器的外观,该错误似乎指向找不到控制器的事实。创建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.");
        }
    }
}

回答

我只是回答了我自己的问题。我有向后的路线(默认在上面)。以下是正确的顺序。因此,这提出了下一个问题..."默认"路由与"页面"路由如何匹配(我假设它们在此处使用正则表达式)?

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
        );

回答

I just answered my own question. I had
  the routes backwards (Default was
  above page).

是的,我们必须将所有自定义路由置于"默认"路由之上。

So this brings up the next question...
  how does the "Default" route match (I
  assume they use regular expressions
  here) the "Page" route?

默认路由根据我们所谓的"约定优于配置"进行匹配。 Scott Guthrie在他关于ASP.NET MVC的第一篇博客文章中对此进行了很好的解释。我建议我们通读它以及他的其他文章。请记住,这些内容是根据第一个CTP发布的,并且框架已更改。我们还可以在Scott.Shan Hanselman的asp.net网站上的ASP.NET MVC上找到网络广播。

  • http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx
  • http://www.asp.net/MVC/

回答

在Rob Conery的MVC店面屏幕录像之一中,他遇到了这个确切的问题。如果我们有兴趣,大约在23分钟左右。