gpt4 book ai didi

c# - 在给定用户已经有 cookie 的情况下启动应用程序时处理 null HttpContext.Current

转载 作者:太空狗 更新时间:2023-10-29 23:45:15 26 4
gpt4 key购买 nike

我正在开发一个网络项目,其中包含使用 cookie 的授权系统。我正在使用 Identity 2.0 示例项目,所以我得到了内置的功能。我还使用 Git 作为我的版本控制系统。

我合并了两个分支。他们都可以轻松地使用授权和 cookie。当您登录然后通过 Visual Studio 停止应用程序时,我可以再次启动该应用程序并且我将保持登录状态。

在我合并了两个分支之后我得到了一些奇怪的行为。我合并的代码不会影响授权系统。

当您登录时会创建 cookie 文件,因此当我通过 Visual Studio 手动停止应用程序然后再次启动它时,我应该已登录。但是应用程序崩溃并出现以下异常:

An exception of type 'System.NullReferenceException' occurred in Microsoft.Owin.Host.SystemWeb.dll but was not handled in user code

Visual Studio 指向以下行:

 var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

该代码包含在 Identity Sample 中,并且在合并之前一直运行良好。正如我所发现的,如果我删除以下代码,该应用程序可以正常运行;我可以停止它并再次运行它,零异常:

 @{
var manager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var currentUser = manager.FindById(User.Identity.GetUserId());
}
@Html.ActionLink("Hello " + currentUser.UserNickName + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

此代码是 _LoggingPartial View 的一部分,它由 Visual Studio 生成并在我合并的分支中修改。

所以现在我完全迷路了,因为我不知道那个异常是由什么引起的。

也许有人可以帮助我,就如何解决它给出建议。

更新:

据我了解,问题不在于昵称。实际上,即使我将以下代码添加到旧版本中,应用程序也会在停止启动后崩溃:

 @{
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var currentUser = userManager.FindById(User.Identity.GetUserId());
}
@Html.ActionLink("Hello " + currentUser.Email.ToString() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

如您所见,此代码不使用任何方法,而是使用 native Identity 的方法。

另外,我测试了不同的方法来获取用户并得到了以下结果:

如果我使用“var currentUser = userManager.FindById(User.Identity.GetUserId());”,应用崩溃

如果我使用“var currentUser = userManager.FindByIdAsync(User.Identity.GetUserId());”,应用崩溃 (当然,我已经修改了其余代码以处理异步结果)

如果我使用“var currentUser = userManager.FindByName(User.Identity.GetUserName());”,应用崩溃

如果我使用“var currentUser = userManager.FindByNameAsync(User.Identity.GetUserName());”,应用不会崩溃

因此,它既不适用于 FindById,也不适用于 FindByIdAsync。如果我使用 FindByName,它可以与 FindByNameAsync 一起使用,但会因简单的 FindByName 而崩溃

最佳答案

找出错误的原因。当我们第一次登录时,我们的用户信息保存在 cookie 中。由于我们使用字符串 Id(在 Identity 中默认),userId = someRandomHash()。也许不是随机的,但无论如何它都不是恒定的。所以,我们的 cookie 中有 randomString1。当我们停止服务器并再次启动它时,数据库将再次生成,因为我们将数据库初始化定义为“DropCreateAlways”。因此,我们的数据库中有 randomString2,但 cookie 中有 randomString1。当我们尝试从 cookie 中获取保存的 Id 时,我们成功获取了它,但是我们无法通过 userManager 在数据库中找到它,因为 Id 现在不同了。

此外,它还解释了为什么使用 GetName() 方法无法重现错误 - 我们始终拥有相同的用户名。而且它只适用于 async Find() 因为它在我们仍然有数据库时运行。然而,简单的非异步方法在数据库已经被删除并且我们在那里没有任何名称时运行。仍然不知道为什么 Visual Studio 会指向“var userManager”行,但我猜这不是很重要。

关于c# - 在给定用户已经有 cookie 的情况下启动应用程序时处理 null HttpContext.Current,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694655/

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