Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

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

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

/MyController/MyAction

I'd like:

/My-Controller/My-Action

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...