|
II6与II7的区别
在使用ASP.NET MVC Framework时,要注意一点II6和II7的区别,如果在II7下,不需要使用.mvc扩展名,路径选择规则可以如下所示:
RouteTable.Routes.Add(
new Route
{
Url = "[controller]/[action]/[id]",
Defaults = new { action = "Index", id = (string)null },
RouteHandler = typeof(MvcRouteHandler)
});
而在II6下,控制器名后面必须要有.mvc扩展名:
RouteTable.Routes.Add(
new Route
{
Url = "[controller].mvc/[action]/[id]",
Defaults = new { action = "Index", id = (string)null },
RouteHandler = typeof(MvcRouteHandler)
});
路径选择规则的验证
在本文第二节我们提到过Route的一个Validation属性,允许我们指定一个路径选择规则匹配需要满足的先决条件。如下代码段所示,验证Id必须为整数且长度在1到8之间:
RouteTable.Routes.Add(
new Route
{
Url = "Blog.mvc/Detail/[id]",
Defaults = new { controller = "Blog", action = "Detail" },
Validation = new { id=@"d{1,8}" },
RouteHandler = typeof(MvcRouteHandler)
});
自定义RouteHandler
在ASP.NET MVC Framework中,提供了很好的扩展功能,如我们可以自定义RouteHandler来实现在Web.config中配置ControllerFactory和ViewFactory。在ASP.NET MVC Framework中,自定义RouteHandler只需要实现IRouteHandler接口并实现GetHttpHandler方法,它的定义如下:
public interface IRouteHandler
{
IHttpHandler GetHttpHandler(RequestContext requestContext);
}
Fredrik在它的Blog上写了一个完整的示例,有兴趣的朋友可以参考一下。 在Web.config中定义路径选择规则ASP.NET MVC Framework中路径选择规则定义在Global.asax中的Application_Start方法中,当映射规则发生改变时,如果修改了Application_Start中的代码,必将导致整个应用程序的重新编译,我们完全可以通过HttpModule来实现把映射规则放在配置文件中。如下示例代码所示:
public class RouteBuilder : IHttpModule
{
public void Init(HttpApplication application)
{
RouteConfiguration routeConfig =
(RouteConfiguration)System.Configuration.ConfigurationManager.GetSection("RouteTable");
foreach (RouteElement routeElement in routeConfig.Routes)
{
Route currentRoute = new Route();
currentRoute.Defaults = new DefaultsType(routeElement.Defaults);
currentRoute.Url = routeElement.Url;
currentRoute.RouteHandler = typeof(MvcRouteHandler);
RouteTable.Routes.Add(currentRoute);
}
}
public void Dispose()
{
}
}
(责任编辑:admin) |