Asp.net-Mvc-5

UserManager 在 ASPNET Identity 2 應用程序中始終為空

  • August 23, 2015

設置:

我有一個 MVC 5 應用程序,其中包含許多庫項目,這些項目是使用我自己的導出模板創建的。導出的模板執行良好。

我正在使用 ASPNET 標識。我只是使用相關 NuGet 包中提供的 Microsoft Aspnet 身份範例的副本,我已將其編織到導出的模板中。這一直運作良好。

我沒有觸及 ASPNET Identity 2 範例中提供的文件。

錯誤發生在 IdentityConfig.cs 文件中。

由於某種原因,它開始出現一個錯誤,指出它無法為 System.Web.Mvc 載入文件,因為它找不到版本 5.1.0.0。

因此,我使用 NuGet 來更新 Microsoft.Aspnet.Mvc 包。這安裝了 system.web.mvc 的 5.2.2.0 版本,這有效地清除了該錯誤。

然而…

儘管應用程序已載入,但每當我嘗試登錄或創建新使用者時,都會出現一個新錯誤(如下所示),基本上說明 ASPNET Identity UserManager 對象為空。

我更新了microsoft.aspnet.identity包,但是在嘗試登錄或者新建使用者的時候還是會出現錯誤(登錄頁面顯示ok,但是點擊登錄按鈕時出現錯誤)

在收到有關 system.web.mvc 參考的錯誤之前,我可以在閒暇時登錄並註冊使用者。

錯誤:

這是我嘗試登錄時顯示的錯誤。當我嘗試註冊一個新使用者時,我得到一個不同的錯誤,但原因相同:UserManager 對象為空,而它不應該是。

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 

問題:

  1. 有誰知道這可能是什麼原因造成的?
  2. 例如,Microsoft Aspnet Identity 範常式式碼是否可能需要針對 system.web.mvc dll 的 5.2.2.0 版本進行更新?

注意:恐怕我無法確定或回憶在錯誤開始發生之前我所做的更改。我已經有一段時間沒有從事這個項目了。

經過一番痛苦,我找到了答案:

出於某種原因,本應包含配置 owin 的程式碼的啟動文件 (~/App_Startup/Startup.Auth.cs) 沒有。不知道這是怎麼發生的。

所以我從 Microsoft.Aspnet.Identity.Samples 程式碼中複製了相應的文件,它現在可以工作了。程式碼是:

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: "");
       }
   }

我以前一直在使用該程式碼,但確實曾經刪除了 owin 包。我沒有手動觸摸文件,所以仍然不確定這是怎麼發生的。

引用自:https://stackoverflow.com/questions/26358044