How to map a route e.g. (site.com/username) in MVC 3

I want to map the route as follows:

mysite.com/username

in an ASP.NET MVC 3 application; How can I do this please? Thanks everyone, welcome

+4
source share
2 answers

Maybe add your own route at the very beginning, which would inherit from System.Web.Routing.Route and override the method

protected virtual bool ProcessConstraint(HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 

where you should check db with an indexed column.

Just add some object with zero constraint like

 Constraints = new { username = "*" } 

so that the route object handles the constraints.

Before deleting the database, perhaps do some heuristics to see if it could be a username. Remember that you cannot have the same name as the controller (with the default action), so you want to somehow restrict this. Please note that if this does not hurt annual performance, but you probably will not have many routes with a single value after the slash.

Here is how you can do it.

 public class UserRoute : Route { public UserRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler) : base(url, defaults, constraints, routeHandler) { } protected override bool ProcessConstraint(HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (routeDirection == RouteDirection.UrlGeneration) return true; object value; values.TryGetValue(parameterName, out value); string input = Convert.ToString(value, CultureInfo.InvariantCulture); // check db if (!CheckHeuristicIfCanBeUserName(input)) { return false; } // check in db if exists, // if yes then return true // if not return false - so that processing of routing goes further return new[] {"Javad_Amiry", "llapinski"}.Contains(input); } private bool CheckHeuristicIfCanBeUserName(string input) { return !string.IsNullOrEmpty(input); } } 

This is an addition at the beginning.

 routes.Add(new UserRoute("{username}", new RouteValueDictionary(){ {"controller", "Home"}, {"action", "About"}}, new RouteValueDictionary(){ { "username", "*" }}, new MvcRouteHandler())); 

Works for me in both directions, generation and use.

+2
source

Maybe something like this?

 routes.MapRoute( "Profile", "{username}", new { controller = "Profile", action = "View" } ); 

With your controller

 public class ProfileController : Controller { public ActionResult View(string username) { // ... } } 
+1
source

All Articles