【问题标题】:how to replace underline with dash in inside area?如何在内部区域用破折号替换下划线?
【发布时间】:2012-10-23 09:23:06
【问题描述】:

我正在为我的网站使用 asp.net MVC 3,我想用我的地址中的破折号替换下划线。我能做到 。但是当我想在一个区域内更换它们时,我做不到。

谁能帮帮我?

这是我的代码:

public class HyphenatedRouteHandler : MvcRouteHandler
        {
            protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
            {
                requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
                requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
                return base.GetHttpHandler(requestContext);
            }
        }

这是我的区域路线:

context.MapRoute(
                "products_default",
                "products/{controller}/{action}",
                new { controller = "All", action = "Index" }
            );

我想浏览这个地址:

localhost:1559/products/store-builder/boronz

product 是我的地区名称。当然,当我浏览这个地址时:

localhost:1559/products/store_builder/boronz

它显示页面。

编辑:

我将它用于我的区域路线,但它无法检测到这是一个区域:

//context.Routes.Add(
//    new Route("products/{controller}/{action}",
//    new RouteValueDictionary(
//        new { controller = "", action = "Index" }),
//        new MyProject.MvcApplication.HyphenatedRouteHandler())
//);

我该如何解决这个问题?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 asp.net-mvc-routing


    【解决方案1】:

    我认为你有一个简单的选择是调整你的路线:

    context.MapRoute(
        "products_default",
        "products/store-builder/{action}",
        new { controller = "YourControllerName", action = "Index" }
    ); 
    

    不过,这样做的缺点是,随着控制器数量的增加,您将需要创建大量路由。另外,我可能已经回答了一个类似的问题here,它创建了一个自定义路由处理程序,就像您的示例开始一样。

    【讨论】:

    • 是的,这是一个简单的选择。但商店建设者是我的产品之一。网站建设者也许是下一个。所以我需要为此创建另一条路线。但我可以为所有这些使用一个模式。
    【解决方案2】:

    你调用 string.replace 错误:第一个参数是旧值,将被第二个参数替换。

    public class HyphenatedRouteHandler : MvcRouteHandler 
        { 
            protected override IHttpHandler GetHttpHandler(RequestContext requestContext) 
            { 
                requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("_", "-"); 
                requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("_", "-"); 
                return base.GetHttpHandler(requestContext); 
            } 
        } 
    

    【讨论】:

    • 这在我在区域外使用时有效。但是在区域中,当我在地址栏中使用破折号时,它找不到地址。
    • @Persian。不幸的是,我不明白您所说的“超出区域”是什么意思,请您多多指教?
    • 我的意思是区域。产品是一个区域。在我的项目中有一个带有 Products name 的区域。
    • @Persian。我注意到您在创建区域路线时没有调用您的自定义路线处理程序:查看here
    • 我把它改成:context.MapRoute("products_default", "products/{controller}/{action}", new { controller = "All", action = "Index" }, new MyProject .MvcApplication.HyphenatedRouteHandler());
    猜你喜欢
    • 2010-11-19
    • 2013-04-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2011-05-07
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多