1

I have a need for some dynamic routing. So my routes would look like this:

{UserName}
{UserName}/Edit/{id}
{UserName}/Delete/{id}

Where the users would be routed to the user controller. But I still want to maintain routes to controls like:

{Controller}/Edit/{id}
{Controller}/Delete/{id}

So basically I want it to direct to the physical controller say called OrdersController for edit delete but if someone navigates to /jdoe/ it sends it to the user controller.

How do I do this in my routes?

1 Answer 1

1

You need to create multiple routes, and keep them in the appropriate order

// one route for Users
routes.MapRoute("Users",
     "{username}/{action}/{id}",
     new { controller = "Users", action = "Index", username = string.Empty, id = UrlParameter.Optional },
     new { id = @"\d+" }
);
// one route for everything else
routes.MapRoute("Default",
     "{controller}/{action}/{id}",
     new { controller = "Home", action = "Index", id = UrlParameter.Optional},
     new { id = @"\d+" }
);

It's not "really" as easy as above, but that's the jist of it. You would need too add a RouteConstraint to validate usernames.

Lastly, if you're using the username parameter, then why do you need the id? Just a thought.


Aside:
If you look at the user section here on StackOverflow, you'll see the routing look more like this.

  • users/{id}/{username}
  • users/{id}/edit
  • users/{id}/delete

I would personally say that this is a lot less work to achieve... but hey, that's just me.

Sign up to request clarification or add additional context in comments.

2 Comments

I may be wrong, I feel the first route will match controller name and not reach the second route and avoid the right controller to handle the request. Pls correct if am wrong.
I've made a minor update to my answer. Basically he would need to add a RouteConstraint

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.