简体   繁体   中英

MVC Routing with Different Param Name in different Controller

I would like MVC to be able to handle the following two urls

http://www.com/Author/Edit/1

http://www.com/Editor/Edit/2

in my AuthorController I have a method:

AuthorController.cs
public void Edit(int AuthorId) {
}

 EditorController.cs
 public void Edit(int EditorId) {
 }

Is this possible, if so, how do I setup the route config to handle this?

This default route has "id" I want a more descriptive var name for each of the action.

I am able to get it to work. But wasn't sure if it is the best practice or the right method.

What I did is created two new entries in the route config to handle the different variations.

Define route for each Edit action in RouteConfig.cs file:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "AuthorEdit",
            url: "author/edit/{AuthorId}",
            defaults: new { controller = "AuthorController", action = "Edit"                    },
            constraints: new { AuthorId= "\\d+" }
        );

        routes.MapRoute(
        name: "EditorEdit",
        url: "editor/edit/{EditorId}",
        defaults: new { controller = "EditorController", action = "Edit" },
        constraints: new { EditorId= "\\d+" }
    );

or if you want use Attribute Routing, modify RouteConfig.cs file:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // Enable attribute routing
        routes.MapMvcAttributeRoutes();

and in controllers:

AuthorController.cs
[Route("author/edit/{AuthorId}")]
public void Edit(int AuthorId) {
}

 EditorController.cs
[Route("editor/edit/{EditorId}")]
 public void Edit(int EditorId) {
 }

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