这让我把头发拉出来。任何帮助将不胜感激。
我在 .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 没有在任务栏中运行,s 仍然保留旧实例。通常,我通过重新启动实例几次或休息 10 分钟然后重新启动来停止它。但可以肯定的是,如果我通过进行该调用的断点进行调试,错误就会回来。
有什么想法或愚蠢的帽子可以给我吗?