How to replace “-” with “_” in url before mapping a controller and an action in a .net mvc3 application

眉间皱痕 提交于 2019-12-24 02:18:28

问题


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();
    }
}

And my corespondent view file is : Foo_Bar.cshtml

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 .

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:)


回答1:


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() 
        ) 
    );  
); 

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




回答2:


Use the attribute [ActionName]

public class Foo_Bar : Controller
{
     [ActionName("foo-bar")]
     public ViewResult Foo_Bar()        
    {

        return View();
    }
}

There isn't an equivalent for Controllers, so you can't use it in your route with {controller}. But you can define it explicitly at least.



来源:https://stackoverflow.com/questions/7708155/how-to-replace-with-in-url-before-mapping-a-controller-and-an-action-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!