我想映射这样的路线:
mysite.com/用户名
在 ASP.NET MVC 3 应用程序中;请问我该怎么做?谢谢大家,问候
也许在一开始就添加自定义路由,继承自 System.Web.Routing.Route,并覆盖方法
protected virtual bool ProcessConstraint(HttpContextBase httpContext, object constraint,
string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
您将在其中使用索引列签入数据库。
只需添加一些不可为空的约束对象,例如
Constraints = new { username = "*" }
这样路由对象将处理约束。
在点击数据库之前,可能会做一些启发式的方法,这是否可以是用户名。请记住,您不能让用户与控制器相同(当有默认操作时),所以您想以某种方式限制它。请注意,如果这不会影响年度表现,但您可能没有很多在斜线后具有单一值的路线。
这就是你可以做到这一点的方法。
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);
}
}
这个加在开头。
routes.Add(new UserRoute("{username}",
new RouteValueDictionary(){ {"controller", "Home"}, {"action", "About"}},
new RouteValueDictionary(){ { "username", "*" }}, new MvcRouteHandler()));
以两种方式为我工作,生成和传入。
也许是这样的?
routes.MapRoute(
"Profile",
"{username}",
new { controller = "Profile", action = "View" }
);
随着你的控制器
public class ProfileController : Controller {
public ActionResult View(string username) {
// ...
}
}