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

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

提交回复
热议问题