.Net MVC:将路由值绑定到会话值

时间:2009-09-03 14:25:23

标签: c# asp.net-mvc asp.net-mvc-routing

我想做以下事情:

用户应该在我的网站上拥有自己的子网站。因此我添加了一条新路线:

routes.MapRoute(
    "ShopEntered",
    "{username}/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);

当第一次调用该站点时,我想在会话中存储用户名值,然后将会话值绑定到路由的用户名部分,这样当我调用Url.Action或Html.ActionLink时,我不要每次都必须设置它。

有谁知道我怎么能意识到这一点?

1 个答案:

答案 0 :(得分:0)

最简单的方法可能是编写自己的帮助方法并使用这些方法而不是Html.ActionLinkUrl.Action。例如:

public static class UserUrlExtensions
{
    // Create whichever overloads you want
    public static string UserActionLink(this HtmlHelper helper, string linkText, RouteValueCollection routeValues)
    {
        // Get whatever value it is you want from the current context
        routeValues["User"] = helper.ViewContext.HttpContext.Current.User.Identity.Name;

        return helper.ActionLink(linkText, routeValues);
    }
}

我不保证它会在没有修改的情况下发挥作用,但你知道如何做这项工作......