Search code examples
c#asp.net-mvcentity-frameworkasp.net-identity

ASP.Net MVC change default string ID to and int using docs get error tho


I made a basic ASP.Net MVC Web project. I switched all my IDs from string to an int with the Microsoft docs.

https://learn.microsoft.com/en-us/aspnet/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity#run

I did these changes + the MVC Update 3 changes. When I compile and run my new project it shows as an int in my file but I get an error and cannot finish running the project.

This is what my messages display in output:

Exception thrown: 'System.FormatException' in mscorlib.dll An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code Input string was not in a correct format.

Any input would be appreciated. I did ran migrations and it shows up as int but doesn’t run in my browser fully.

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, int>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => 
                        user.GenerateUserIdentityAsync(manager), 
                        getUserIdCallback:(id)=>Int32.Parse(id.GetUserId()))
                }
            });

My code breaks in this part and that is the exception id.GetUserId()

This is in startup.auth.cs

Thank you.


Solution

  • So to put it as an answer to your question, the Parse method uses the current locale to convert your string to integer. I would guess that in your case, the GetUserID() would be in a format that your current locale would expect a comma as decimal point. Hence giving the optional parameter CultureInfo.InvariantCulture would make your locale culture-insensitive. An alternative would be provide a second optional parameter to provide a IFormatProvider.

    To resolve your error, set this line as:

    (id)=>Int32.Parse(id.GetUserId(),CultureInfo.InvariantCulture)
    

    For more information on CultureInfo.InvariantCulture.

    Cheers.