0

I'm new to MVC and URL routing, and am looking for some guidance.

I would like to be able to have a URL per user, with the format: http://www.example.com/username

So I added the following route:

routes.MapRoute(
    "UserRoute", // Route name
    "{username}", // URL
    new { controller = "Users", action = "ViewUser", username = UrlParameter.Optional }
);

Which works great if it is the FIRST route, but it has messed up the default {controller}/{action}/{id} route. Now when I try to visit the root page, it tries to load my UsersController "ViewUser" action with a null parameter (or with "favicon.ico" as the parameter).

If I put my new route AFTER the default route, then MVC tries to find the controller called username and fails because it can't find it.

Is there any way to have URLs of the form {username} without mucking up the regular routing system? I could probably write a custom route for every controller I have, but that seems error-prone.

1
  • You are right, routing is error-prone. Checkout mvccoderouting.codeplex.com if you want to completely forget about routing issues. Commented Mar 11, 2011 at 13:23

2 Answers 2

1

You can check out this link and see if it helps. It is also creating urls with just a username on them.

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

1 Comment

This solution (which uses reflection to find all the other controllers) seems a little odd, but I suppose it should work. I guess this particular URL scheme isn't one that the MVC team anticipated.
1

You can put a constraint to the allowed controller values for the default route, instead of creating a route for each controller.

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL
    new { controller = "controller1", action = "defaultaction", id = UrlParameter.Optional }, //default values
    new { controller = @"controller1|controller2|controller3|..." }
);

when the controller does not match any of those it will try the next route

2 Comments

This might work, but it's not really any better than listing each controller individually. I still have to remember to list each and every one, and I KNOW that in a year I'm going to add a new controller and then spend an hour battling 404's before I remember about the routing hack I used.
@Henry, it is problem of logic. Since both your routes satisfy the root url, you is the computer to understand what to load ? it just uses the first on. You could change your UserRoute url to be "user/{username}" to fix it, but that changes the url pattern you want..

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.