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

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

问题描述

是否有一种简单的方法可以让 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.

这样我就可以在继续使用 MapRoute 方法的同时支持诸如 sample.com/test-page/edit-details 映射到 Action edit_details 和 Controller 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.MapRoute 替换为等效的 routes.Add 即可指定新的路由处理程序.这是必需的,因为 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()))

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

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