问题描述
如果您查看一个SO问题的URL,你会看到一个ID和一个弹头传递给控制器的问题:http://stackoverflow.com/questions/676934/what-do-you-need-to-write-your-own-blog-engine.我觉得有趣的是,您可以更改URL的弹头部分,而不会影响应用程序的能力,将请求路由的的。我能想到的拉这一关的唯一方法是有一个接受一个ID和一个弹头,并用在塞的路径约束,以确保它遵循一个模式的路线。我不得不使用约束,以确保具有两个变量不导致匹配的所有请求该路由。有没有人有更好的方式来做到这一点,或更先进的路由方案的例子?
加法:
我认识的弹头是人类可读性 - ,我想在另一个应用程序重复此功能。什么是实现这一目标的最佳途径。
路线:
routes.MapRoute(
编号+弹头,//路线名称
测试/ {ID} / {}塞,// URL带参数
新//参数默认
{
控制器=测试,
行动=详细信息,
ID =,
塞=
},
新{蛞蝓=新SlugConstraint()}
);
简单的约束:
公共类SlugConstraint:IRouteConstraint
{
公共BOOL匹配(HttpContextBase HttpContext的,
路线路线,
字符串参数名称,
RouteValueDictionary值,
RouteDirection routeDirection)
{
字符串值=值[参数名称]的ToString(); 返回value.Contains( - );
}
}
这你在找什么...它没有在最后定义蛞蝓。
If you review a SO question URL you will see that an ID and a "SLUG" are passed to the Questions controller: http://stackoverflow.com/questions/676934/what-do-you-need-to-write-your-own-blog-engine. What I find interesting is you can change the "SLUG" portion of the URL without affecting the application's ability to route the request example. The only way I could think to pull this off is have a route that accepted an id and a "SLUG" and used a route constraint on the slug to ensure it followed a pattern. I had to use a constraint to ensure that having the two variables didn't result in this route matching all requests. Does anyone have a better way to accomplish this, or any examples of more advanced routing scenarios?
ADDITION:
I realize the SLUG is for human readablity, and I would like to duplicate this feature in another application. What is the best way to accomplish this.
Route:
routes.MapRoute(
"Id + Slug", // Route name
"Test/{id}/{slug}", // URL with parameters
new // Parameter defaults
{
controller = "Test",
action = "Details",
id = "",
slug = ""
},
new { slug = new SlugConstraint() }
);
Simple Constraint:
public class SlugConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
string value = values[parameterName].ToString();
return value.Contains("-");
}
}
Is this what you're looking for...it doesn't define the slug at the end.
这篇关于堆栈溢出问题路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!