简体   繁体   中英

MVC Default route with nullable id not working as expected

A simple routing scenario is not working for me.

my route registration looks like this

context.MapRoute(
                "Users_default",
                "Users/{controller}/{action}/{id}",
                new { action = "Index", id= UrlParameter.Optional });

and i am expecting it to honor the requests for

users/profile/
users/profile/1
users/profile/2

with the following controller

 public class ProfileController : Controller
    {
        public ActionResult Index(int? id)
        {
            var user = id == null ? (UserModel)HttpContext.Session["CurrentUser"] : userManager.GetUserById((int)id);
            return View(user);
        }
    }

it works for users/profile but not for users/profile/1 i've tried few different things but i know the answer must be simple, its just my lack of knowledge, what am i missing here.

This is because your route interprets as:
{controller: "profile", action: "1"} .

You need to point you details action url explicit, something like this:
users/profile/index/1

You can use Attribute routing

The code would look like

public class ProfileController : Controller
{
    [Route("users/profile/{id}")]
    public ActionResult Index(int? id)
    {
        var user = id == null ? (UserModel)HttpContext.Session["CurrentUser"] : userManager.GetUserById((int)id);

        return View();
    }
}

And you have to modify your RouteConfig

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

        // This will enable attribute routing in your project
        routes.MapMvcAttributeRoutes();

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

So now you can use users/profile for your default behaviour and users/profile/ for a specific profile.

i dont want index to appear. i want to use the same method for both users/profile/1 and users/profile/

Then don't put action into your URL.

context.MapRoute(
    "Users_default",
    "Users/{controller}/{id}",
    new { action = "Index", id= UrlParameter.Optional });

The route you have defined will not allow index to be optional because it is followed by another parameter (in this case "id"). Only the last parameter can be optional on all but the default route.

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