0
我正在開發ASP.NET的MVC應用程序,並且需要在用戶登錄到站點後在URL中顯示用戶名。在路由(URL)中顯示用戶名Asp.net MVC 4
我正在開發ASP.NET的MVC應用程序,並且需要在用戶登錄到站點後在URL中顯示用戶名。在路由(URL)中顯示用戶名Asp.net MVC 4
我希望我已經正確理解你的問題 - 我很抱歉,如果我沒有。
創建自定義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() }
);
你有沒有你正在使用的代碼的例子? – James