ASP.Net MVC Route to Username

后端 未结 5 1200
难免孤独
难免孤独 2020-12-22 17:39

I am trying to create a route with a Username...

So the URL would be mydomain.com/abrudtkhul (abrudtkhul being the username)

My application will have public

5条回答
  •  粉色の甜心
    2020-12-22 18:26

    You might want to consider not allowing usernames of certain types if you want to have some other functional controllers like Account, Admin, Profile, Settings, etc. Also you might want your static content not to trigger the "username" route. In order to achieve that kind of functionality (similar to how twitter urls are processed) you could use the following Routes:

    // do not route the following
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("content/{*pathInfo}"); 
    routes.IgnoreRoute("images/{*pathInfo}");
    
    // route the following based on the controller constraints
    routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        , new { controller = @"(admin|help|profile|settings)" } // Constraints
    );
    
    // this will catch the remaining allowed usernames
    routes.MapRoute(
        "Users",
        "{username}",
        new { controller = "Users", action = "View", username = "" }
    );
    

    Then you will need to have a controller for each of the tokens in the constraint string (e.g. admin, help, profile, settings), as well as a controller named Users, and of course the default controller of Home in this example.

    If you have a lot of usernames you don't want to allow, then you might consider a more dynamic approach by creating a custom route handler.

提交回复
热议问题