with tutorial password net mvc lockout existing asp asp.net-mvc-5 asp.net-identity-2

asp.net-mvc-5 - tutorial - asp.net core identity password requirements



UserManager siempre nulo en la aplicaciĆ³n ASPNET Identity 2 (1)

Preparar:

Tengo una aplicación MVC 5 con varios proyectos de biblioteca, creada usando mis propias plantillas exportadas. Las plantillas exportadas han estado funcionando bien.

Estoy usando ASPNET Identity. Solo estoy usando una copia de la muestra de identidad de Aspnet de Microsoft que se incluye en el paquete NuGet correspondiente, que he entretejido en mis plantillas exportadas. Esto ha estado funcionando bien.

No he tocado los archivos proporcionados en la muestra ASPNET Identity 2.

El error ocurre en el archivo IdentityConfig.cs.

Por alguna razón, comenzó a aparecer un error que indicaba que no podía cargar el archivo para System.Web.Mvc, ya que no podía encontrar la versión 5.1.0.0.

Como resultado, utilicé NuGet para actualizar el paquete Microsoft.Aspnet.Mvc. Esta versión instalada de 5.2.2.0 de system.web.mvc, y esto efectivamente borró ese error.

Sin embargo...

Aunque la aplicación se carga, cada vez que trato de iniciar sesión o crear un nuevo usuario, aparece un nuevo error (que se muestra a continuación), que básicamente establece que el objeto de ASPNET Identity UserManager era nulo.

Actualicé el paquete microsoft.aspnet.identity, pero el error aún ocurre al intentar iniciar sesión o crear un nuevo usuario (la página de inicio de sesión muestra OK, pero el error ocurre al hacer clic en el botón de inicio de sesión)

Antes de obtener el error con respecto a la referencia system.web.mvc, podría iniciar sesión y registrar usuarios en mi tiempo libre.

Error:

Este es el error que se muestra cuando intento iniciar sesión. Cuando trato de registrar un nuevo usuario, aparece un error diferente, pero con la misma causa: el objeto UserManager es nulo, cuando no debería ser.

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 324: public async Task<SignInStatus> PasswordSignIn(string userName, string password, bool isPersistent, bool shouldLockout) Line 325: { Line 326: var user = await UserManager.FindByNameAsync(userName); Line 327: if (user == null) Line 328: { Source File: c:/Users/[user name]/Documents/Visual Studio 2013/Projects/[My solution]/Models/IdentityConfig.cs Line: 326

Pregunta:

  1. ¿Alguien sabe lo que podría estar causando esto?

  2. Podría, por ejemplo, ser posible que el código de muestra de Microsoft Aspnet Identity necesite actualizarse para la versión 5.2.2.0 del sistema.web.mvc dll?

NOTA: Me temo que no puedo determinar o recordar lo que cambié justo antes de que comenzaran los errores. No he estado trabajando en este proyecto por un tiempo.


Después de mucho dolor, encontré la respuesta:

Por alguna razón, el archivo de inicio (~ / App_Startup / Startup.Auth.cs), que se suponía debía contener código para configurar owin, no lo hizo. No estoy seguro de cómo sucedió esto.

Así que copié el archivo correspondiente del código Microsoft.Aspnet.Identity.Samples y ahora funciona. El código es:

public partial class Startup { // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and role manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.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( // clientId: "", // clientSecret: ""); } }

He estado usando el código anteriormente, pero eliminé los paquetes de owin en un punto. No toqué el archivo manualmente, así que aún no estoy seguro de cómo sucedió esto.