繁体   English   中英

ASP.Net MVC路由映射

[英]ASP.Net MVC route mapping

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

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

上面的代码不会将* .aspx映射到PageController吗? 当我运行它并输入任何.aspx页面时,我收到以下错误:

无法找到路径“/Page.aspx”的控制器,或者它没有实现IController接口。 参数名称:controllerType

有什么我不在这里做的吗?

我刚回答了自己的问题。 我向后退了路线(默认在页面上方)。 以下是正确的订单。 所以这就提出了下一个问题......“默认”路由如何匹配(我假设它们在这里使用正则表达式)“Page”路由?

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

我刚回答了自己的问题。 我向后退了路线(默认在页面上方)。

是的,您必须将所有自定义路由放在默认路由之上。

所以这就提出了下一个问题......“默认”路由如何匹配(我假设它们在这里使用正则表达式)“Page”路由?

默认路由根据我们称之为约定优于配置的内容进行匹配。 Scott Guthrie在他关于ASP.NET MVC的第一篇博文中很好地解释了这一点。 我建议你仔细阅读它以及其他帖子。 请记住,这些是基于第一个CTP发布的,并且框架已经更改。 您还可以在Scott Hanselman的asp.net网站上找到ASP.NET MVC上的网络广播。

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

您可以通过MvcRouteVisualizer测试路线

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM