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

前端 未结 9 1004
礼貌的吻别
礼貌的吻别 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:33

    You can use the ActionName attribute like so:

    [ActionName("My-Action")]
    public ActionResult MyAction() {
        return View();
    }
    

    Note that you will then need to call your View file "My-Action.cshtml" (or appropriate extension). You will also need to reference "my-action" in any Html.ActionLink methods.

    There isn't such a simple solution for controllers.

    Edit: Update for MVC5

    Enable the routes globally:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapMvcAttributeRoutes();
        // routes.MapRoute...
    }
    

    Now with MVC5, Attribute Routing has been absorbed into the project. You can now use:

    [Route("My-Action")]
    

    On Action Methods.

    For controllers, you can apply a RoutePrefix attribute which will be applied to all action methods in that controller:

    [RoutePrefix("my-controller")]
    

    One of the benefits of using RoutePrefix is URL parameters will also be passed down to any action methods.

    [RoutePrefix("clients/{clientId:int}")]
    public class ClientsController : Controller .....
    

    Snip..

    [Route("edit-client")]
    public ActionResult Edit(int clientId) // will match /clients/123/edit-client
    
    0 讨论(0)
  • I've developed an open source NuGet library for this problem which implicitly converts EveryMvc/Url to every-mvc/url.

    Uppercase urls are problematic because cookie paths are case-sensitive, most of the internet is actually case-sensitive while Microsoft technologies treats urls as case-insensitive. (More on my blog post)

    NuGet Package: https://www.nuget.org/packages/LowercaseDashedRoute/

    To install it, simply open the NuGet window in the Visual Studio by right clicking the Project and selecting NuGet Package Manager, and on the "Online" tab type "Lowercase Dashed Route", and it should pop up.

    Alternatively, you can run this code in the Package Manager Console:

    Install-Package LowercaseDashedRoute

    After that you should open App_Start/RouteConfig.cs and comment out existing route.MapRoute(...) call and add this instead:

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

    That's it. All the urls are lowercase, dashed, and converted implicitly without you doing anything more.

    Open Source Project Url: https://github.com/AtaS/lowercase-dashed-route

    0 讨论(0)
  • 2020-11-28 22:37

    Asp.Net MVC 5 will support attribute routing, allowing more explicit control over route names. Sample usage will look like:

    [RoutePrefix("dogs-and-cats")]
    public class DogsAndCatsController : Controller
    {
        [HttpGet("living-together")]
        public ViewResult LivingTogether() { ... }
    
        [HttpPost("mass-hysteria")]
        public ViewResult MassHysteria() { }
    }
    

    To get this behavior for projects using Asp.Net MVC prior to v5, similar functionality can be found with the AttributeRouting project (also available as a nuget). In fact, Microsoft reached out to the author of AttributeRouting to help them with their implementation for MVC 5.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 22:42

    I'm still pretty new to MVC, so take it with a grain of salt. It's not an elegant, catch-all solution but did the trick for me in MVC4:

    routes.MapRoute(
        name: "ControllerName",
        url: "Controller-Name/{action}/{id}",
        defaults: new { controller = "ControllerName", action = "Index", id = UrlParameter.Optional }
    );
    
    0 讨论(0)
  • 2020-11-28 22:48

    You can define a specific route such as:

    routes.MapRoute(
        "TandC", // Route controllerName
        "CommonPath/{controller}/Terms-and-Conditions", // URL with parameters
        new {
            controller = "Home",
            action = "Terms_and_Conditions"
        } // Parameter defaults
    );
    

    But this route has to be registered BEFORE your default route.

    0 讨论(0)
提交回复
热议问题