gpt4 book ai didi

c# - ASP.NET MVC5 标识 : Avoid changing logged-in user after registration

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:29 25 4
gpt4 key购买 nike

我想更改 MVC5 ASP.NET 应用程序的默认注册操作。我的场景是这样的,授权用户(例如管理员)将登录并可以创建新用户。但是使用下面的代码片段,在创建用户后,当前登录的用户将更改为注册用户。

如何更改以下代码以避免更改登录用户?

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName,Name=model.Name };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}

// If we got this far, something failed, redisplay form
return View(model);
}

最佳答案

只需这样做:

if (result.Succeeded)
{
if (!User.IsAuthenticated) // if they're already logged in, don't log in again
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}

关于c# - ASP.NET MVC5 标识 : Avoid changing logged-in user after registration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35728908/

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