What I want to do is like Facebook profile page which is (facebook.com/username) , I'd like to do the same thing ww开发者_如何学JAVAw.myapplication/username , is there any routing method ??
To route to a profile page, you need a route with a RouteConstraint to check the validity of the username. Your route must be the first route, and RegisterRoutes in Global.asax.cs should look like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Profiles", // Route name
"{username}", // URL
new { controller = "Profile", action = "Index" }, // Parameters
new { username = new MustBeUsername() }
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Then, you must create a RouteConstraint class which will check you database to confirm that the username submitted is valid:
using System;
using System.Web;
using System.Web.Routing;
namespace ExampleApp.Extensions
{
public class MustBeUsername : IRouteConstraint
{
public MustBeUsername() { }
private DbContext _db = new DbContext();
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return (_db.Users.Where(u => u.Username == values[parameterName].ToString()).Count() > 0);
}
}
}
counsellorben
精彩评论