我有一个使用Microsoft Open ID连接进行用户身份验证的ASP.NET应用程序。我不会在我的数据库中存储任何密码。虽然我使用asp Identity存储角色和声明。
我需要一种方式,以便我可以登录"作为任何用户进行测试。
控制器:
#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>
}
}
问题
为什么代码示例我在第二次尝试而不是第一次尝试,我该如何纠正?
更新
添加了RedirectToAction
[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");
}
此代码现在正在运行,但我仍然不了解原始方法失败的原因?
答案 0 :(得分:1)
而不是POST
方法return View(model);
- 您可以尝试:
return RedirectToAction("LoginOffline");