1

I'm building a small MVC application. After a user logs in I want his/her route to display:

www.appname.com/username/

Underneath of course same action is called for each user e.g. /home/index. How do I write my MapRoute to achieve that and what other code(attributes) should I use?

tereško
  • 58,060
  • 25
  • 98
  • 150
mishap
  • 8,176
  • 14
  • 61
  • 92
  • What characters are authorized in a username? Do you allow a user to register on your site with username = Home/Index for example? – Darin Dimitrov Mar 25 '12 at 15:42
  • @Darin Dimitrov, Usernames will have no special characters. I'm building it mostly for learning purposes, so nothing overly complex, just want to have user to log in and see a custom url that could be shared with other people. – mishap Mar 25 '12 at 16:21

1 Answers1

1

Add this rout to your routes in global.asax.cs file

  routes.MapRoute(
            "RouteName", // Route name
            "FixedUrlSegment/{UserName}/{Controller}/{action}/{id}/", // URL with parameters
            new { controller = "ControllerName", 
                  action = "ActionName",
                  id=UrlParameter.Optional
                }, 
        );

I think you should use a fixed segment as start-up point for your route to distinguish it from default or other routes

of course in log in action method you must redirect to that new route

return RedirectToRoutePermanent("RouteName", new { username = "UserName",
                                                   action = "Index", 
                                                   controller = "Home",
                                                   id="userId"
                                                 }
                                );
// remember id is not required for that route as mentioned in global file

this example will redirect your page to url

www.appname.com/FixedUrlSegment/loggedusername/home/index/loggeduserid

Amir Ismail
  • 3,865
  • 3
  • 20
  • 33