身份核心2注册问题

时间:2017-10-09 17:42:12

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

我正在尝试使用模型来创建使用asp.net core 2 sql server和identity core的用户。但是我在注册用户时遇到问题以下是我的代码及其生成的错误。我希望有人可以帮助我。

这不仅仅是一个空问题,因为发布表格时没有得到正确的模型,因此人员的插入不正确。

型号:

public class Register
{

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

我有一个标有post命令的注册操作

[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
        ViewData["ReturnUrl"] = returnUrl;
        return View();
}

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(AppUser model, string returnUrl = null)
{
        ViewData["ReturnUrl"] = returnUrl;

            var user = new AppUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                //    "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                await _signInManager.SignInAsync(user, isPersistent: false);
                   return RedirectToLocal(returnUrl);
            }



        // If we got this far, something failed, redisplay form
        return View(model);
}

这是我的表格

的html
@model solitude.models.Register
@{
    ViewData["Title"] = "Register";
    Layout = "~/Views/Shared/_LoginAdminLte.cshtml";
}



<body class="hold-transition register-page">
<div class="register-box">
    <div class="register-logo">
        <a href="../../index2.html"><b>Register</b></a>
    </div>
    <div class="register-box-body">
        <p class="login-box-msg">Register a new membership</p>
        <form asp-controller="Account" asp-action="Register" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal" role="form">

            <div class="form-group has-feedback">
                <input type="text" class="form-control" placeholder="Full name">


                <span class="glyphicon glyphicon-user form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">

                <input asp-for="Email" class="form-control" placeholder="Email"> 

                <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">
                <input asp-for="Password" class="form-control" />

                <span class="glyphicon glyphicon-lock form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">
                <input asp-for="ConfirmPassword" class="form-control" />

                <span class="glyphicon glyphicon-log-in form-control-feedback"></span>
            </div>
            <div class="row">
                <div class="col-xs-8">
                    <div class="checkbox icheck">
                        <label>
                            <input type="checkbox"> I agree to the <a href="#">terms</a>
                        </label>
                    </div>
                </div>
                <!-- /.col -->
                <div class="col-xs-4">
                    <button type="submit" class="btn btn-primary btn-block btn-flat">Register</button>
                </div>
                <!-- /.col -->
            </div>
        </form>

但我遇到以下错误问题

  

System.NullReferenceException:未将对象引用设置为实例   一个对象。在   solitude.admin.core.Controllers.AccountController.d__6.MoveNext()   在   C:\项目\ solitudeec2core \ solitude.admin.core \ solitude.admin.core \ \控制器AccountController.cs:行   88   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()   在   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   

的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

当我看第88行时,它显示了这一点,但我不明白为什么我遇到这个问题

  

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

我的Startup.cs

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        var connection = @"Server=----SEVER NAME HIDDEN---;Database=solitude;Trusted_Connection=True;";

        services.AddDbContext<SolitudeDBContext>(options => options.UseSqlServer(connection));
        services.AddIdentity<AppUser, IdentityRole>()
         .AddEntityFrameworkStores<SolitudeDBContext>()
         .AddDefaultTokenProviders();

        services.AddMvc();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

是否有任何机构知道可能出现的问题。

1 个答案:

答案 0 :(得分:0)

错误在这一行:

public async Task<IActionResult> Register(AppUser model, string returnUrl = null)

您应该提供注册类型作为模型输入参数,而不是 AppUser

public async Task<IActionResult> Register(Register model, string returnUrl = null)
相关问题