对URL的连字符ASP.net MVC支持 [英] ASP.net MVC support for URL's with hyphens

查看:173
本文介绍了对URL的连字符ASP.net MVC支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法来获得MvcRouteHandler在进来的URL的动作和控制器部分中的所有连字符转换为下划线连字符不是在方法或类名的支持。

Is there an easy way to get the MvcRouteHandler to convert all hyphens in the action and controller sections of an incoming URL to underscores as hyphens are not supported in method or class names.

这会是这样我就可以支持这样的结构,如sample.com/test-page/edit-details~~V映射到行动edit_details和控制器test_pagecontroller同时继续使用图路线的方法。

This would be so that I could support such structures as sample.com/test-page/edit-details mapping to Action edit_details and Controller test_pagecontroller while continuing to use MapRoute method.

我明白我可以指定一个动作名称属性和支持连字符控制器名称这出手动添加路由来实现这个,但是我正在寻找一个自动化的方式,以便将错误保存增加新的控制器和动作的时候。

I understand I can specify an action name attribute and support hyphens in controller names which out manually adding routes to achieve this however I am looking for an automated way so save errors when adding new controllers and actions.

推荐答案

我已经研究出了解决办法。在MvcRouteHandler内的的RequestContext包含了控制器和动作上,你可以做一个简单的替换值。

I have worked out a solution. The requestContext inside the MvcRouteHandler contains the values for the controller and action on which you can do a simple replace on.

Public Class HyphenatedRouteHandler
    Inherits MvcRouteHandler

    Protected Overrides Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler
        requestContext.RouteData.Values("controller") = requestContext.RouteData.Values("controller").ToString.Replace("-", "_")
        requestContext.RouteData.Values("action") = requestContext.RouteData.Values("action").ToString.Replace("-", "_")
        Return MyBase.GetHttpHandler(requestContext)
    End Function

End Class

然后,所有你需要用等效routes.Add指定新的路由处理程序来代替routes.MapRoute。这是必须的,因为图路线不允许您指定一个自定义的路由处理。

Then all you need to replace the routes.MapRoute with an equivalent routes.Add specifying the the new route handler. This is required as the MapRoute does not allow you to specify a custom route handler.

routes.Add(New Route("{controller}/{action}/{id}", New RouteValueDictionary(New With {.controller = "Home", .action = "Index", .id = ""}), New HyphenatedRouteHandler()))

这篇关于对URL的连字符ASP.net MVC支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆