如何替换” - "与" _"在URL映射之前的控制器,并在.NET应用程序MVC3行动 [英] How to replace "-" with "_" in url before mapping a controller and an action in a .net mvc3 application

查看:135
本文介绍了如何替换” - "与" _"在URL映射之前的控制器,并在.NET应用程序MVC3行动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好:我的工作。净MVC3应用程序。 这是我的控制器和动作:

Hello everyone :I am working on a .net mvc3 application. Here is my controller and action :

public class Foo_Bar : Controller
{
     public ViewResult Foo_Bar()        
    {

        return View();
    }
}

和我corespondent视图文件是:Foo_Bar.cshtml

And my corespondent view file is : Foo_Bar.cshtml

现在,我的问题是:我有一个网址为:www.mystite.com/foo-bar/foo-bar 但这个网址无法调用foo_bar这样的名称/ foo_bar这样的控制器和动作,除非我把它写成THES:www.mystite.com/foo_bar/foo_bar

now ,my question is : I have a url as: www.mystite.com/foo-bar/foo-bar but this url can not invoke the Foo_Bar/Foo_Bar controller and action except I write it as thes: www.mystite.com/foo_bar/foo_bar .

现在我需要更换 - 和_的路线系统映射我的控制器和行动之前。我能做到这一点,在routes.MapRoute()?有人请帮助我。谢谢你提前!PS:这是我第一次问堆栈溢出的问题:)

Now I need to replace the "-" with "_" before the route system mapping my controller and action. Can I do it in the routes.MapRoute()? Some one please help me .Thank you advance !ps:this is my first time to ask an question in Stack overflow:)

推荐答案

您可以创建自定义 RouteHandler 更改值 {行动} {控制器} 。首先,创建你RouteHandler,如下:

You can create a custom RouteHandler to change the values for {action} and {controller}. First, create your RouteHandler, as follows:

using System.Web.Mvc;  
using System.Web.Routing;  

public class MyRouteHandler : IRouteHandler  
{  
    public IHttpHandler GetHttpHandler(RequestContext requestContext)  
    {  
        var routeData = requestContext.RouteData;  
        var controller = routeData.Values["controller"].ToString(); 
        routeData.Values["controller"] = controller.Replace("-", "_");  
        var action = routeData.Values["action"].ToString();  
        routeData.Values["action"] = action.Replace("-", "_");  
        var handler = new MvcHandler(requestContext);  
        return handler;  
    }  
}  

然后,改变你的默认路由如下:

Then, change your Default route as follows:

routes.Add("Default",  
    new Route("{controller}/{action}/{id}",  
        new RouteValueDictionary(  
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }),  
            new MyRouteHandler() 
        ) 
    );  
); 

当一个请求是通过这条线路满足时,RouteHandler将改变破折号下划线。

When a request is satisfied by this route, the RouteHandler will change the dashes to underbars.

这篇关于如何替换” - "与" _"在URL映射之前的控制器,并在.NET应用程序MVC3行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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