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

发布于 2024-08-03 23:13:50 字数 351 浏览 4 评论 0原文

我想要执行以下操作:

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

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

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

有谁知道我如何才能实现这一点?

I want to do the following:

The user should have his own sub site on my web site. Therefor I've added a new route:

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

When the site gets called for the first time I want to store the username value in the session and then bind the session value to the username part of the route, so that when I call Url.Action or Html.ActionLink I don't have to set it every time manualy.

Does anyone know how I could realize this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故事灯 2024-08-10 23:13:50

最简单的方法可能是编写自己的辅助方法并使用这些方法来代替 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);
    }
}

我不保证它无需修改即可工作,但您知道如何完成工作......

The easiest way would probably be to write your own helper methods and use these instead of Html.ActionLink and Url.Action. For example:

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

I don't guarantee that it will work without modification, but you get the idea of how to do the work...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文