如何解决UserManager "A second operation started on this context" 错误仅在使用断点调试时
这让我把头发拔了。任何帮助都将不胜感激。
我正在 .NET 框架 4.6.1 中运行一个 MVC(我相信是 5 个)应用程序。我正在使用身份验证。大约一年前,我在旧电脑上创建了这个网站。在过去的一年里,我断断续续地研究它,从来没有遇到过这个问题。然后最近,我买了一台新笔记本电脑,从 GitHub 克隆了这个项目,突然间我遇到了这个奇怪的问题,每当我调试和单步执行调用它的某个地方时,UserManager 都会给我这个“第二次操作”错误,这我的网站上有很多地方。它从未在我的旧机器上对我这样做过,所以我不知道是不是需要更改设置,或者我是否偶然遗漏了旧机器上的一些代码,尽管这似乎不太可能。
我以默认方式设置了我的 UserManager,将其创建为 OwinContext 的一部分。
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<AppUsersDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
requiredLength = 6,RequireNonLetterOrDigit = true,requiredigit = true,RequireLowercase = true,RequireUppercase = true,};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code",new PhoneNumberTokenProvider<ApplicationUser>
{
messageformat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code",new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context,user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(AppUsersDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationoptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager,ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),regenerateIdentity: (manager,user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option,your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberbrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberbrowserCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",// clientSecret: "");
//app.UseTwitterauthentication(
// consumerKey: "",// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2Authenticationoptions()
//{
// ClientId = "",// ClientSecret = ""
//});
}
}
如您所见,这一切都非常标准,至少就我所知。我什至认为自 Visual Studio 创建此代码以来,我从未对它进行过任何重大修改。
当它被调用时,概念是我的父控制器有一个 AppUser 属性,以便我可以获得有关当前用户的任何信息,我需要进行数据存储调用。为了获得这个 AppUser,我调用了 UserManager 和 FindByName。
public ApplicationUser AppUser
{
get
{
if (appUser == null) { appUser = UserManager.FindByName(User.Identity.Name); }
return appUser;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetowinContext().GetUserManager<ApplicationUserManager>();
}
set
{
_userManager = value;
}
}
然后我在如下示例中调用该 AppUser:
[HttpPost]
[HasAccess(Priviledge = AppLogic.Priviledge.DM)]
public JsonResult Updateactivitylog(activitylogPostModel model)
{
try
{
CampaignSvc.Updateactivitylog(AppUser.UserId,AppUser.ActiveCampaign.Value,model.ArcKey,model.LogKey,model.LogDescription,model.Type,model.ContentKey);
}
catch (Exception ex)
{
return Json(new { success = false,message = ex.Message });
}
return Json(new { success = true,message = "Log added successfully!" });
}
上面的例子只是众多例子中的一个。这与这个特定实例无关。我几乎可以选择站点中的任何地方。所以让我出现这个“第二个操作”错误的一件事是我什至没有调用调用的异步版本。可以说我应该,但我不是,但我仍然收到这个错误。因此,最重要的是,在使用 localhost 在调试模式下运行站点时,我没有收到此错误。我可以在网站上执行任何我需要的操作,而且我没有遇到任何问题。但是在随机时间,如果我在调试和单步执行时有一个断点,我的操作就会失败并且我会收到这个“第二次操作”异常,这在我的旧计算机上从未发生过一次。我可以停止实例并重新启动它,它会立即给我这个错误,就像即使 IIS Express 没有在任务栏中运行,它仍然保留旧实例。通常,我通过重新启动实例几次或休息 10 分钟然后重新启动来使其停止。但可以肯定的是,如果我通过调用该调用的断点进行调试,错误又会回来。
有什么想法或笨蛋给我吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。