ASP.NET 用于开发环境的 MVC 5 登录后门



我有一个使用 Open ID connect 进行用户身份验证Microsoft ASP.NET 应用程序。我不在我的数据库中存储任何密码。虽然我确实使用 asp 标识存储角色和声明。

我需要一种方法,以便我可以以任何用户身份"登录"进行测试。

控制器:

#if DEBUG
[AllowAnonymous]
[HttpGet]
public ActionResult LoginOffline()
{
        if (Request.IsLocal == false)
        {
            return HttpNotFound();
        }
        List<ApplicationUser> model = UserManager.Users.ToList();
        return View(model);
}
[AllowAnonymous]
[HttpPost]
public async Task<ActionResult> LoginOffline(string id)
{
     if (Request.IsLocal == false) 
         return HttpNotFound();
     ApplicationUser user = UserManager.FindById(id);
     if (user != null)
     {
            await SignInManager.SignInAsync(user, true, true);
     }
     List<ApplicationUser> model = UserManager.Users.ToList();
     return View(model);
}
#endif

如您所见,请求需要是本地的,并且项目在 DEBUG 模式下打开。

@model System.Collections.Generic.List<ApplicationUser>
<h2>Super Secret Login Page</h2>
<h3> Currently Logged in as @User.Identity.Name</h3>   
@using (Html.BeginForm("LoginOffline", "Account", new {ViewBag.ReturnUrl}))
{
  foreach (var user in Model)
  {
     <div class="row form-group col-lg-offset-1">
     <button type="submit" class="btn btn-primary pull-left" id="@user.Id" name="id" value="@user.Id" title="Login as @user.FirstName @user.LastName">Sign in as @user.UserName</button>
     <span>
         @foreach (var role in user.Roles)
         {
         @role 
             @Html.Raw(", ");
         }
     </span>
     </div>
     }
}

问题

为什么我的代码示例在第二次尝试中工作,而不是第一次尝试,我该如何纠正它?

更新

添加了重定向到操作

        [AllowAnonymous]
    [HttpPost]
    public async Task<ActionResult> LoginOffline(string id)
    {
        if (Request.IsLocal == false) return HttpNotFound();
        ApplicationUser user = UserManager.FindById(id);
        if (user != null)
        {
            await SignInManager.SignInAsync(user, true, true);
        }
        return RedirectToAction("LoginOffline");
    }

这段代码现在可以工作了,但我仍然不明白为什么原始方法失败了?

而不是你的POST方法return View(model); - 你能试试:

return RedirectToAction("LoginOffline");

最新更新