gpt4 book ai didi

c# - 保持配置文件 ID 可通过应用程序访问

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:03 24 4
gpt4 key购买 nike

我有以下创建乐队资料的代码:

    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。

最佳答案

关于这样做的“正确性”存在一些争论(链接如下),但您可以将变量存储在 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 question处理同样的问题,here是另一个。

编辑:

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

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

var bandProfile = BandProfile.Profile;

根据 Microsoft :

ASP.NET includes application state primarily for compatibility with classic ASP so that it is easier to migrate existing applications to ASP.NET. It is recommended that you store data in static members of the application class instead of in the Application object.

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

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

关于c# - 保持配置文件 ID 可通过应用程序访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36500229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com