[英]Auto login for debugging ASP.NET MVC 5
我見過
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,但沒有運氣。 登錄頁面仍然會觸發。 我已經嘗試在Login中添加一個檢查,頁面永遠不會加載
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中這樣做的方法是什么?
在您的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
此代碼也僅包含在調試版本中。
剛試過它,應該可以正常工作。 請享用 :)
這對我沒有用,我需要修改Adams對此的回復。 我使用的是VS2013和MVC 5。
將AutoLogin的簽名更改為:(注意任務后的新'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");
希望這有助於某人。 這對我來說很有用。 Cheers.Jon
這就是為我做的事情; 很簡單:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.