开发者

ASP.NET MVC Url routing problems

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://w开发者_运维百科ww.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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜