วันศุกร์ที่ 12 ธันวาคม พ.ศ. 2557

การแก้ปัญหาหลังจากอัพเดท MVC แล้วเกิด Object reference not set to an instance of an object. โดย Microsoft.Owin.Security.Cookies.CookieAuthenticationProvider.Exception

ตรงจุดนี้ เราจะไม่สามารถรันหรือ Debug อะไรได้เลย  เนื่องจาก Error ตั้งแต่ Start เลย  ลองค้นดู
            
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)),

                        //**** This what I add ****//
                        OnException = context => {}
                }
            });

โดยการแสดงปัญหาจากตัว Authentication นั้น เอามาจากที่นี่

http://stackoverflow.com/questions/26327092/why-is-owin-throwing-a-null-exception-on-new-project

โดยเพิ่ม OnException เข้าไป จะพบกับ Error
Multiple object sets per type are not supported. The object
 sets 'ApplicationUsers' and 'Users' can both contain instances of type 
'CommandTracking.Models.User'.
แทน  ทีนี้ ลอง ค้นหาดูจะพบว่า ปัญหานี้ เกิดจาก ตัว Update ของ EntityFramework ที่เพิ่ม IDbset<TUser> Users ขึ้นมา ทำให้หากใน Project ของเรา มีตัว DbSet<ApplicationUser> เอาไว้ จะทำให้ เกิดการซ้ำซ้อนกันได้  แก้ไขโดย ลบ DbSet<ApplicationUser> ที่สร้างขึ้นเอง และ แก้ไขตัว db.<user> ที่เราใช้ ให้ไปใช้ db.Users แทน