ASP.NET MVC Overriding Index action with optional

2019-05-23 03:04发布

问题:

I want to accept /User/ and /User/213123

Where 213123 is a parameter (user_id)

Here is my RouteConfig.cs:

            routes.MapRoute(
                name: "user",
                url: "{controller}/{action}/{username}",
                defaults: new { controller = "User", action = "Index", username = UrlParameter.Optional }
            );

And my UserController.cs:

        public ActionResult Index()
        {
            ViewData["Message"] = "user index";
            return View();
        }

        [Route("user/{username}")]
        public ActionResult Index(string username)
        {
            ViewData["Message"] = "!" + username + "!";
            return View();
        }

This works in .net-core 1.0 but not in mvc5. What am I missing?

Thank you

EDIT:

Having just this in my UserController.cs also doesn't work (returns 404):

        public ActionResult Index(string username)
        {
            if (!String.IsNullOrEmpty(username))
            {
                ViewData["Message"] = "Hello " + username;
            }
            else
            {
                ViewData["Message"] = "user index";
            }

            return View();
        } 

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /user/asd

EDIT2:

Updated RouteConfig.cs:

        routes.MapRoute(
            "userParam", "user/{username}",
          new { controller = "user", action = "IndexByUsername" },
          new { username = @"\w+" }
        );

        routes.MapRoute(
            name: "user",
            url: "user",
            defaults: new { controller = "User", action = "Index"}
        );

/User/ now calls IndexByUsername with Index as the username

/User/asd still returns 404

EDIT4: Current code:

RouteConfig.cs:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/",
            defaults: new { controller = "Home", action = "Index" }
        );
routes.MapRoute("userParam", "user/{username}", new { controller = "user", action = "Index"});
routes.MapRoute("user", "{controller}/{action}/{username}", new { controller = "User", action = "Index", username = UrlParameter.Optional });

UserController.cs:

public class UserController : Controller
{
    public ActionResult Index(string username)
    {
        if (!String.IsNullOrEmpty(username))
        {
            ViewData["Message"] = "Hello " + username;
        }
        else
        {
            ViewData["Message"] = "user index";
        }

        return View();
    }
}

回答1:

You need only one action method with the signature

public ActionResult Index(string username)

and in that method you can check if the value of username is null or not.

Then you route definitiosn needs to be (note the user route needs to be placed before the default route)

routes.MapRoute(
    name: "user",
    url: "user/{username}",
    defaults: new { controller = "User", action = "Index", username = UrlParameter.Optional }
);
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);