ASP.NET MVC 5的自动登录调试

3

我看到过这个问题:

ASP.NET Forms身份验证 - 在调试期间使用测试帐户自动登录?

在开发期间ASP.NET站点自动登录

但这些都是针对较旧版本的ASP.NET MVC(请查看帖子上的日期)。

我尝试添加了

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (System.Diagnostics.Debugger.IsAttached && User == null)
    {
        FormsAuthentication.SetAuthCookie("user1@contoso.com", true);
    }
}

尝试访问global.aspx,但没有成功。登录页面仍然触发。我已经在登录页面中添加了一个检查,但页面从未加载。

public ActionResult Login(string returnUrl)
{
    if (System.Diagnostics.Debugger.IsAttached && User.Identity.IsAuthenticated == false)
    {
        var x = new LoginViewModel() { Email = "user1@contoso.com", Password = "Pa55w0rd!", RememberMe = false };
        Login(x, returnUrl).Wait();
        return View(x);
    }

    ViewBag.ReturnUrl = returnUrl;
    return View();
}

但是当我导航到需要身份验证的页面时,网页会无限制地加载(如果我进行调试,则会触发SignInManager.PasswordSignInAsync(),但是永远不会返回(在AccountController中的自动生成代码)。

ASP.NET mvc 5中有什么解决方法吗?


你可以在不改变代码的情况下实现这一点,只需要进行webconfig更改和一个登录示例应用程序即可。如果您认为这个解决方案可行,我可以分享更多细节。 - Rajshekar Reddy
3个回答

1

在您的HomeController或任何您想要设置默认启动URL的地方

#if DEBUG
        public async Task AutoLogin()
        {
if (System.Diagnostics.Debugger.IsAttached) { var controller = DependencyResolver.Current.GetService(); controller.InitializeController(Request.RequestContext); return await controller.Login(new LoginViewModel() { Email = "user@no.com", Password = "passwordHere", RememberMe = false }, "/Home/Index"); }
return Content("Not debugging"); } #endif

并修改您的AccountController以包含

using System.Web.Routing;

#if DEBUG
        public void InitializeController(RequestContext context)
        {
            base.Initialize(context);
        }
#endif

这段代码仅适用于调试版本。

刚刚测试过,应该可以正常工作。享受吧 :)


1
这就是我所做的,非常简单:

public ActionResult Login()
{
  if (System.Diagnostics.Debugger.IsAttached)
  {
    var controller = DependencyResolver.Current.GetService<AccountController>();
    controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);
    return controller.Login("toddmo","abc123");
  }
  return View();
}

0

这对我来说并没有直接起作用,我需要修改亚当的回复。我正在使用VS2013和MVC 5。

将AutoLogin的签名更改为此:(请注意,在Task后面添加了新的“ActionResult”)

public async Task<ActionResult> AutoLogin()

需要将依赖解析器行更改为以下内容:

AccountController controller = (AccountController) DependencyResolver.Current.GetService(typeof (AccountController));

我还将返回URL从“Home\Index”更改为简单的“Home”,但我不确定是否有所不同。

最后,我将“return Content("Not debugging");”更改为:

return View("Index");

希望这能帮助到某些人。对我来说它运行良好。干杯,Jon。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接