【问题标题】:Keep profile id accessible through the application保持可通过应用程序访问的个人资料 ID
【发布时间】:2016-04-08 13:00:20
【问题描述】:

我有以下代码可以创建乐队简介:

    var bandProfile = _profileService.CreateBandProfile(model.BandProfile, file, UserId);

    if (bandProfile != null)
    {
        userManager.AddToRole(UserId, "Band");
        //Store the bandprofile ID anywhere?
        return RedirectToAction("Index", "Welcome");
    }

不,我想存储bandprofile ID 并使之可以通过应用程序访问。在用户使用个人资料登录时保持可访问性。

我怎样才能做到这一点?

例如,要获取 userId,您可以通过应用程序这样做:

UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();

我想做同样的事情,但使用的是 bandprofileId。

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    关于这样做的“正确性”存在一些争议(链接如下),但您可以将变量存储在HttpContext.Current.Application["BandProfile"]

    if (bandProfile != null)
    {
        userManager.AddToRole(UserId, "Band");
        //Store the bandprofile ID anywhere?
        HttpContext.Current.Application["BandProfile"] = bandProfile;
    
        return RedirectToAction("Index", "Welcome");
    }
    

    或者,您可以在某处的类中使用static 变量。

    public static class BandProfile
    {
        public static whatever Profile;
    }
    
    if (bandProfile != null)
    {
        userManager.AddToRole(UserId, "Band");
        //Store the bandprofile ID anywhere?
        BandProfile.Profile = bandProfile;
    
        return RedirectToAction("Index", "Welcome");
    }
    

    这是处理相同问题的related questionhere 是另一个。

    编辑:

    要访问这些变量,您可以使用

    var bandProfile = HttpContext.Current.Application["BandProfile"];

    var bandProfile = BandProfile.Profile;

    根据Microsoft

    ASP.NET 包含应用程序状态,主要是为了与经典 ASP 兼容,以便更容易将现有应用程序迁移到 ASP.NET。建议您将数据存储在应用程序类的静态成员中,而不是应用程序对象中。

    也就是说,您应该使用static 变量方法。静态变量可通过调用ClassName.Variable 获得,并且将在应用程序运行期间存在。如果应用程序关闭或变量以其他方式更改,您将丢失此信息。

    为了保存信息,需要将此变量的内容写入外部源(数据库、文件等)并在应用启动时读取。

    【讨论】:

    • 当我为类变量赋值时,该值是否“永远”存储在该变量中?
    • @Bryan 我正在尝试为您找到更具体的答案,但我的理解是该变量是在用户会话期间设置的。它不会成为“永远”存在的全局变量。
    • 不过,您可能需要为此使用HttpContext.Current.Session。让我看看我能找到什么
    • 另外 - 如果你使用 static 类,这将在应用程序运行期间被重置,除非值被保存(例如到 DB)并读入之后。不过,我无法告诉您这将如何与同时访问内容的多个用户一起工作。
    • @Bryan 我已经更新了答案,包括来自微软的一些信息(以及我自己的结论)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    相关资源
    最近更新 更多