Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-identity

Problems creating an applicationuser via register page in mvc project?


I'm having a weird problem and I found several threads on this site that address the exact problem I'm having, but they to seem to all be able to fix their problem by setting the securitystamp in the applicationuser before running the Createasync method and making the user.

Except that doesn't solve anything for me, I keep getting an exception where it says the "value" parameter can't be null.

Here is my extended applicationuser class:

public class ApplicationUser : IdentityUser
    {

        [Required]
        [Display(Name = "Fornavn")]
        [StringLength(50, MinimumLength = 0, ErrorMessage = "Titlen skal være på mellem 6 og 50 tegn")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Efternavn")]
        [StringLength(50, MinimumLength = 0, ErrorMessage = "Titlen skal være på mellem 6 og 50 tegn")]
        public string LastName { get; set; }

        [Required]
        [Display(Name = "E-mail")]
        [StringLength(50, MinimumLength = 0, ErrorMessage = "Titlen skal være på mellem 6 og 50 tegn")]
        public string Email { get; set; }

        [Display(Name = "Profilbillede")]
        public String ProfileImagePath { get; set; }

        [Display(Name = "Uddannelsessted")]
        [StringLength(50, MinimumLength = 0, ErrorMessage = "Titlen skal være på mellem 6 og 50 tegn")]
        public String Institution { get; set; }

        [Display(Name = "")]
        [StringLength(50, MinimumLength = 0, ErrorMessage = "Titlen skal være på mellem 6 og 50 tegn")]
        public String Semester { get; set; }

        [Display(Name = "Speciale")]
        [StringLength(50, MinimumLength = 0, ErrorMessage = "Titlen skal være på mellem 6 og 50 tegn")]
        public String Major { get; set; }

        [Display(Name = "Niveau")]
        public int? Level { get; set; }

        [Display(Name = "Jobtitel")]
        [StringLength(50, MinimumLength = 0, ErrorMessage = "Titlen skal være på mellem 6 og 50 tegn")]
        public String Position { get; set; }

        [Display(Name = "Kort beskrivelse")]
        [StringLength(1000, MinimumLength = 100, ErrorMessage = "Titlen skal være på mellem 100 og 1000 tegn")]
        public String Description { get; set; }

        public int CurrentCase { get; set; }

        public int CurrentExamSet { get; set; }


    }

And this is my Register method in the account controller:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase image)
        {

            if (ModelState.IsValid)
            {

                var user = model.GetUser();
                if (image != null)
                {
                    if (!Directory.Exists(Server.MapPath("~") + "/Images/ProfileImages"))
                        Directory.CreateDirectory(Server.MapPath("~") + "/Images/ProfileImages/");
                    var guid = Guid.NewGuid().ToString();
                    DataHelper.ResizeAndSave(Server.MapPath("~") + "/Images/ProfileImages/", guid, image.InputStream, 170);
                    user.ProfileImagePath = Server.MapPath("~") + "/Images/ProfileImages/" + guid + ".jpg";
                }
                else
                {
                    user.ProfileImagePath = "";
                }
                user.SecurityStamp = Guid.NewGuid().ToString();
                var result = await UserManager.CreateAsync(user, model.Password);             

                if (result.Succeeded)
                {
                    return RedirectToAction("Index", "Home");
                }

            }

            // If we got this far, something failed, redisplay form

            return View(model);

        }

It crashes on this exact line:

var result = await UserManager.CreateAsync(user, model.Password);

I've tried setting every single field value (Even in the base class) to something so that there isn't even a single field value in the applicationuser class that is null, but the error pops up anyway.

If anyone could help I would be grateful, cuz this problem is seriously annoying and I can't get further in my project.

Stacktrace:

[ArgumentNullException: En værdi må ikke være null.
Parameternavn: value]
   System.ComponentModel.DataAnnotations.ValidationContext.set_DisplayName(String value) +48859
   System.Data.Entity.Utilities.ValidationContextExtensions.SetDisplayName(ValidationContext validationContext, InternalMemberEntry property, DisplayAttribute displayAttribute) +274
   System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +106
   System.Data.Entity.Internal.Validation.PropertyValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +148
   System.Data.Entity.Internal.Validation.EntityValidator.ValidateProperties(EntityValidationContext entityValidationContext, InternalPropertyEntry parentProperty, List`1 validationErrors) +203
   System.Data.Entity.Internal.Validation.TypeValidator.Validate(EntityValidationContext entityValidationContext, InternalPropertyEntry property) +105
   System.Data.Entity.Internal.Validation.EntityValidator.Validate(EntityValidationContext entityValidationContext) +55
   System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items) +295
   System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items) +86
   Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`1.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items) +2946
   System.Data.Entity.DbContext.GetValidationErrors() +290
   System.Data.Entity.Internal.InternalContext.SaveChangesAsync(CancellationToken cancellationToken) +143
   System.Data.Entity.Internal.LazyInternalContext.SaveChangesAsync(CancellationToken cancellationToken) +66
   System.Data.Entity.DbContext.SaveChangesAsync(CancellationToken cancellationToken) +60
   System.Data.Entity.DbContext.SaveChangesAsync() +63
   Microsoft.AspNet.Identity.EntityFramework.<SaveChanges>d__0.MoveNext() +148
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.AspNet.Identity.EntityFramework.<CreateAsync>d__5.MoveNext() +403
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +984
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   Microsoft.AspNet.Identity.<CreateAsync>d__10.MoveNext() +883
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   MEV3.Controllers.<Register>d__1a.MoveNext() in c:\Users\Little\Desktop\ASP.NET\MEV3\MEV3\Controllers\AccountController.cs:252
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   lambda_method(Closure , Task ) +64
   System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +64
   System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
   System.Web.Mvc.Async.<>c__DisplayClass34.<BeginInvokeAsynchronousActionMethod>b__33(IAsyncResult asyncResult) +65
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c() +117
   System.Web.Mvc.Async.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e() +323
   System.Web.Mvc.Async.<>c__DisplayClass30.<BeginInvokeActionMethodWithFilters>b__2f(IAsyncResult asyncResult) +44
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
   System.Web.Mvc.Async.<>c__DisplayClass28.<BeginInvokeAction>b__19() +72
   System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>b__1b(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651116
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Get user method:

public ApplicationUser GetUser()
        {

            var user = new ApplicationUser()

            {

                UserName = this.UserName,

                FirstName = this.FirstName,

                LastName = this.LastName,

                Email = this.Email,

                ProfileImagePath = ProfileImagePath,

                Semester = Semester,

                Major = "",

                Level = 1,

                Institution = Institution,

                Position = "Praktikant",

                Description = Description,

                CurrentCase = 0,

                CurrentExamSet = 0

            };
            return user;

        }

When I step through the code, the error pops up right after it completes this method in the accountcontroler:

protected override void Dispose(bool disposing)
        {
            if (disposing && UserManager != null)
            {
                UserManager.Dispose();
                UserManager = null;
            }
            base.Dispose(disposing);
        }

Solution

  • Its not the SecurityStamp, its the Email property that fails on validation. IdentityUser already has an Email property so Email property of ApplicationUser "hides" the IdentityUser property. Remove Email property from ApplicationUser to solve the probleme. Email is already required in IdentityUser. The other annotations for your localized error messages and labels put them on your RegisterViewModel.