我正在开发ASP.NET的MVC应用程序,并且要求是在用户登录到站点后在URL中显示用户名。
答案 0 :(得分:2)
我希望我能正确理解你的问题 - 如果我没有,我道歉。
创建自定义RouteConstraint
在我的示例中,我检查URL是否与登录用户的用户名匹配。如果用户名匹配,则路由有效,并且将调用主控制器上的索引操作。
如果用户名是heymega ..
http://localhost:48735/heymega/有效
http://localhost:48735/chris/无效
public class UserNameRoute : IRouteConstraint
{
public bool Match(System.Web.HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
//Get the username from the URL
var username = values["username"].ToString();
if (httpContext.User.Identity.IsAuthenticated)
{
//Compare the username to the logged in user
return httpContext.User.Identity.Name == username;
}
return false;
}
}
定义支持约束的路线
routes.MapRoute(
name: "UserNameRoute",
url: "{username}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { username = new UserNameRoute() }
);