简体   繁体   中英

How can I replace _ with - in my URL in ASP.NET MVC3?

I have my controller names set up as "My_Controller". I'm looking for a way to change my URL from www.mysite.com/My_Controller/My_Action to www.mysite.com/my-controller/my-action/ .

Is there anyway to do this without using a URL re-writer extension? If so, how?

You can use a routehandler.

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

..and add it to your route like this:

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
        ).RouteHandler = new HyphenatedRouteHandler();

This will mean that, whenever you have a controller named "Example_Controller" with an action called "Example_Action", you will be able to call it with /example-controller/example-action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM