ASP.NET 路由 - 避免控制器/操作和虚荣/slug url 之间的冲突
我正在寻找一个很好的解决方案,让 URL 方案既适用于标准 ASP.NET MVC 控制器/操作 url,例如:
/Home/About --> Controller "Home", Action "About"
也适用于虚荣/slug url,例如:
/fred/post --> Controller "Posts", Action "View", User "fred", Post "post"
重要的是,我希望出站 url 生成能够工作,以便
Html.ActionLink("View", "Posts", new { User="fred", Post="post" }, null }
提供 /fred /post - 不是 /Posts/View/fred/post
看来,我可以让它适用于入站或出站路由,但不能同时适用于两者。或者我可以让它工作,但它很混乱并且容易损坏。有什么方法、技巧和窍门可以让这样的事情干净利落地工作?
I'm looking for a good solution to having a URL scheme that works for both standard ASP.NET MVC controller/action urls eg:
/Home/About --> Controller "Home", Action "About"
and vanity/slug urls eg:
/fred/post --> Controller "Posts", Action "View", User "fred", Post "post"
Importantly, I want the outbound url generation to work so that
Html.ActionLink("View", "Posts", new { User="fred", Post="post" }, null }
gives /fred/post - not /Posts/View/fred/post
It seems, I can get it to work for either inbound or outbound routing but not both. Or I can get it sort of working but it's messy and prone to breaking. What approaches, tips and tricks are there to getting something like this working cleanly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最终想出了使用路由约束的解决方案,该约束可以检查参数是否与控制器的名称匹配(或不匹配):
像这样使用:
约束
new ControllerConstraint(false)
表示如果参数与控制器名称匹配,则不匹配此路由规则。传递 true 以使约束检查参数是否与控制器名称匹配。I finally came up with the solution of using a routing constraint that can check if a parameter matches (or doesn't match) the name of a controller:
Use like this:
The constraint
new ControllerConstraint(false)
means don't match this routing rule if the parameter matches the name of a controller. Pass true to make the constraint check that the parameter does match a controller name.