Asp.Net MVC: How do I enable dashes in my urls?

前端 未结 9 1052
礼貌的吻别
礼貌的吻别 2020-11-28 21:52

I\'d like to have dashes separate words in my URLs. So instead of:

/MyController/MyAction

I\'d like:

/My-Controller/My-Act         


        
9条回答
  •  野性不改
    2020-11-28 22:41

    Here's what I did using areas in ASP.NET MVC 5 and it worked liked a charm. I didn't have to rename my views, either.

    In RouteConfig.cs, do this:

     public static void RegisterRoutes(RouteCollection routes)
        {
            // add these to enable attribute routing and lowercase urls, if desired
            routes.MapMvcAttributeRoutes();
            routes.LowercaseUrls = true;
    
            // routes.MapRoute...
        }
    

    In your controller, add this before your class definition:

    [RouteArea("SampleArea", AreaPrefix = "sample-area")]
    [Route("{action}")]
    public class SampleAreaController: Controller
    {
        // ...
    
        [Route("my-action")]
        public ViewResult MyAction()
        {
            // do something useful
        }
    }
    

    The URL that shows up in the browser if testing on local machine is: localhost/sample-area/my-action. You don't need to rename your view files or anything. I was quite happy with the end result.

    After routing attributes are enabled you can delete any area registration files you have such as SampleAreaRegistration.cs.

    This article helped me come to this conclusion. I hope it is useful to you.

提交回复
热议问题