我想做的是像Facebook个人资料页面(facebook.com/username),我想做同样的事情www.myapplication / username,有没有路由方法?
答案 0 :(得分:0)
要路由到个人资料页面,您需要一个包含RouteConstraint的路由来检查用户名的有效性。您的路由必须是第一个路由,Global.asax.cs中的RegisterRoutes应如下所示:
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
);
}
然后,您必须创建一个RouteConstraint类,它将检查您的数据库以确认提交的用户名是否有效:
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