2009-02-06 154 views
0

我试图实现路由有问题,如下列:与MVC路由

帖子/ 535434 /这 - 是 - 一 - 后标题

posts/tagged/tags+here 
// Matches {controller}/{action}/{id} - Default 
// Displays all posts with the specified tags 
// uses PostsController : ActionTagged(string tags) 

posts?pageSize=50&pageIndex=4 
// Matches {controller}/{action}/{id} - Default 
// Displays all posts 
// uses PostsController : Index(int? pageSize, int? pageIndex) 

这是我想的问题这样做:

posts/39423/this-is-a-post-title-here 
// Typically this is implemented using an action like 'Details' 
// and would normally look like : posts/details/5 

我似乎无法得到路由工作的权利。我想是这样的:

{controller}/{id}/{description} 

并设置默认操作为“显示”的作品,但后来也不会允许我导航到像“标记”等命名的动作。

我错过了什么?

谢谢!

回答

1

两件事情:

首先,你应该经常整理你的航线减少的特异性(例如,最具体案例第一,至少特定情况下最后一个),这样线路将“落空”,如果不匹配它将尝试下一个。

所以我们要定义{控制器}/{}帖子ID/...(必须是一个帖子ID)之前,我们定义{控制器}/{行动}/...(可能是别的)

接下来,我们希望能够指定,如果为postid提供的值看起来不像Post ID,则路由应该失败并进入下一个。

public class PostIDConstraint : IRouteConstraint 
{ 
    public bool Match(HttpContextBase httpContext, 
    Route route, 
    string parameterName, 
    RouteValueDictionary values, 
    RouteDirection routeDirection) 
    { 
    //if input looks like a post id, return true. 
    //otherwise, false 
    } 
} 

我们可以将其添加到路由定义,像这样:我们可以通过创建一个IRouteConstraint类做到这一点

routes.MapRoute(
    "Default", 
    "{controller}/{postid}/{description}", 
    new { controller = "Posts", action = "Display", id = 0 }, 
    new { postid = new PostIDConstraint() } 
); 
+0

好的答案。虽然问题。我需要在IRouteContraint中做些什么?我从来没有用过它,你能否再解释一下。 – Micah 2009-02-06 13:06:10

0

我不是100%我明白你的问题,但它听起来像你可以定义几条不同的路线。

routes.MapRoute("PostId", "posts/{id}/{title}", 
    new { Controller = "Posts", Action = "DisplayPost", id = 0, title = "" }, 
    new { id = @"\d+" }); 

routes.MapRoute("TaggedPosts", "posts/tagged/{tags}", 
    new { Controller = "Posts", Action = "DisplayTagged", tags = "" }); 

routes.MapRoute("Default", "posts", 
    new { Controller = "Posts", Action = "Index" }); 

您可以使用正则表达式就像我在第一路用于ID验证的参数,或者如果你想一些更好的验证这样做雷克斯中号公布。查询字符串参数pageSize和pageIndex不需要包含在您的路由中;只要参数名称匹配,它们就会被传递给您的索引方法。