更改 ASP.NET MVC 3 控制器路由行为
假设我有一些名称很长的控制器,例如 VeryLongNameController。
默认情况下,ASP.NET MVC3 会将 ~/VeryLongName 或 ~/verylongname 映射到此控制器。不过,我不喜欢在 URL 中使用大写名称,并希望它映射所有长命名控制器,例如 ~/very-long-name。
我知道可以一一添加自定义路由,但是有没有办法更改默认行为?
Let's say I have a few controllers with long names like VeryLongNameController.
By default ASP.NET MVC3 will map ~/VeryLongName or ~/verylongname to this controller. However I don't like the use of capital names within the URL and would like it to map all long named controllers like ~/very-long-name instead.
I know that it's possible to add custom routes one by one, but is there a way to change the default behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以,您需要提供自己的路由处理程序实现
IRouterHandler
,有一个很好的例子此处。You can, you need to provide your own route handler implementing
IRouterHandler
, there's a good example here.您可以专门针对操作方法使用 ActionName 属性。但不是控制器。
另外 - 我更喜欢为每个控制器/操作方法添加路由,这样我就不会创建任何意外的映射(我单位也测试它们) - 所以这是需要考虑的一件事。
You can use an ActionName attribute specifically for an action method.. not a controller though
Also - I prefer to add a route for every controller/action method so I don't create any unexpected mappings (I unit test them as well too) - so this is one thing to consider.
我对此进行了更多研究,并通过制作自己的 IHttpHandler 和 IRouteHandler 来使其工作,查看 System.Web.Mvc.MvcHandler 和 System.Web.Mvc.MvcRouteHandler 并基本上复制、粘贴和替换它的解析方式控制器名称。然而,我根本不喜欢这种方法,因为对于一个简单的装饰任务来说,重做整个请求处理管道感觉太重了。因此,我将为每个具有两个名称(数量不多)的控制器添加手动路由。
更新:我提出了一个更简单的解决方案,这是通过重写 ControllerFactory 来完成的。
我关于它的博客文章: http://cangencer.wordpress.com/2011/05/27/better-looking-urls-in-asp-net-mvc-3/
I've investigated this a bit more, and got it working by making my own IHttpHandler and IRouteHandler, looking at the source for System.Web.Mvc.MvcHandler and System.Web.Mvc.MvcRouteHandler and basically copying and pasting and replacing how it resolves the controller name. However I don't like this approach at all, as it feels too heavy-weight to redo the whole request processing pipe for a simple cosmetic task. Thus, I will go with adding manual routes for each controller which has two names (which there aren't that many).
UPDATE: I've come with a much simpler solution, and that is done through overriding ControllerFactory .
My blog post about it: http://cangencer.wordpress.com/2011/05/27/better-looking-urls-in-asp-net-mvc-3/