在mvc项目中通过注册页面创建applicationuser的问题?

时间:2014-11-21 10:47:51

标签: c# asp.net-mvc asp.net-mvc-5 asp.net-identity

我遇到了一个奇怪的问题,我发现这个网站上有几个线程解决了我遇到的确切问题,但他们似乎都能通过设置安全性问题来解决问题。在运行Createasync方法并创建用户之前的applicationuser。

除非我没有为我解决任何问题,否则我会在其中显示"值"参数不能为空。

这是我的扩展applicationuser类:

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; }


    }

这是帐户控制器中的Register方法:

[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);

        }

它崩溃了这条确切的行:

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

我已尝试将每个字段值(即使在基类中)设置为某些内容,以便即使applicationuser类中的单个字段值为null,但错误仍会弹出

如果有人可以提供帮助,我将不胜感激,因为这个问题非常烦人,我无法在我的项目中取得进一步的发展。

堆栈跟踪:

[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

获取用户方法:

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;

        }

当我单步执行代码时,错误会在accountcontroler中完成此方法后立即弹出:

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

2 个答案:

答案 0 :(得分:2)

它不是SecurityStamp,它的Email属性在验证时失败。 IdentityUser已经拥有Email属性,因此Email属性为ApplicationUser&#34;隐藏&#34} IdentityUser属性。 从Email移除ApplicationUser属性以解决问题。 Email中已经需要IdentityUser。您的本地化错误消息和标签的其他注释会将其放在RegisterViewModel上。

答案 1 :(得分:0)

我有一个使用本地显示名称的解决方案。其中一些没有所有可用语言的价值。显示剃须刀页面时此方法正常,该页面使用默认语言。

但是由于某种原因,在将实体保存到数据库时不起作用(当然,“为什么EF为什么使用保存时赋予属性的显示”仍然悬而未决)?

此行提示原因

 System.ComponentModel.DataAnnotations.ValidationContext.set_DisplayName(String value) +48859

然后你有这个

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

它不是null,但删除空值可能会有所帮助。