Asp.net mvc 在路由(URL)Asp.net MVC 4中显示用户名

Asp.net mvc 在路由(URL)Asp.net MVC 4中显示用户名,asp.net-mvc,routes,Asp.net Mvc,Routes,我正在开发ASP.NET的MVC应用程序,要求在用户登录到站点后在URL中显示用户名 我希望我正确理解了你的问题-如果我没有理解,我道歉 创建自定义RouteConstraint routes.MapRoute( name: "UserNameRoute", url: "{username}", defaults: new { controller = "Home", action = "Index" },

我正在开发ASP.NET的MVC应用程序,要求在用户登录到站点后在URL中显示用户名

我希望我正确理解了你的问题-如果我没有理解,我道歉

创建自定义RouteConstraint

        routes.MapRoute(
            name: "UserNameRoute",
            url: "{username}",
            defaults: new { controller = "Home", action = "Index" },
            constraints: new { username = new UserNameRoute() }
        );
在我的示例中,我检查URL是否与登录用户的用户名匹配。如果用户名匹配,则路由有效,并且将调用主控制器上的索引操作

如果用户名是heymega

这是有效的

将是无效的

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() }
        );

您是否有正在使用的代码的示例?