ASP.NET Core 2.0身份-密码错误消息未在视图中显示

时间:2018-07-13 18:45:33

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

使用默认的ASP.NET Identity服务时遇到问题。一切正常,但尝试注册帐户时,如果不满足密码复杂性,则不会显示任何错误消息。

我运行了调试器,以下是抛出的错误:

result  {Failed : PasswordTooShort,PasswordRequiresDigit,PasswordRequiresUpper,PasswordRequiresUniqueChars} Microsoft.AspNetCore.Identity.IdentityResult

错误消息未传递到视图中以显示在“密码”字段上。您如何将错误传递到视图中?我可以手动创建一个模型状态错误,但希望改为传递预配置的消息。

任何帮助将不胜感激。

**更新,我能够提取错误消息,但是试图解决如何将所有消息传递到视图中。现在,该视图仅显示第一条错误消息。我需要遍历视图中的所有错误消息来做到这一点吗?如果是这样,最好的方法是什么?


我已经在 startup.cs 中配置了以下服务:

public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


            services.AddIdentity<IdentityUser, IdentityRole>()
                    .AddEntityFrameworkStores<AppDbContext>();

            services.Configure<IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit = true;
                options.Password.RequiredLength = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = true;
                options.Password.RequireLowercase = false;
                options.Password.RequiredUniqueChars = 6;
            });
            services.AddTransient<IFeedbackRepository, FeedbackRepository>();
            services.AddTransient<IPieRepository, PieRepository>();
            services.AddMvc();
        }

我的帐户控制器的配置如下:

public class AccountController : Controller
    {
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly UserManager<IdentityUser> _userManager;


            public AccountController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
            {
                _signInManager = signInManager;
                _userManager = userManager;
            }

            public IActionResult Register()
            {
                return View(new LoginViewModel());
            }


             [HttpPost]
    public async Task<IActionResult> Register(LoginViewModel loginViewModel)
    {
        if (ModelState.IsValid)
        {
            var user = new IdentityUser() { UserName = loginViewModel.UserName };
            var result = await _userManager.CreateAsync(user, loginViewModel.Password);

            if (result.Succeeded)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                var errList = "";
                var error = result.Errors.ToList(); //convert to list

                foreach (var err in error) //iterate through individual error
                {
                    this.ModelState.AddModelError("Password", err.Description); //add error to modelstate
                    //errList += string.Join(", ", err.Description);
                }
                //this.ModelState.AddModelError("Password", errList);

            }
        }


        return View(loginViewModel);
    }

登录视图模型配置为:

        public class LoginViewModel
        {
            [Key]
            [Required]
            [Display(Name ="User Name")]
            public string UserName { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }
        }
    }

用于注册的视图配置为:

@model LoginViewModel

<h2>Register</h2>

<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Register" asp-controller="Account" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="UserName" class="control-label"></label>
                <input asp-for="UserName" class="form-control" />
                <span asp-validation-for="UserName" class="text-danger"></span><br />
                <label asp-for="Password" class="control-label"></label>
                <input asp-for="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Register" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

我无法轻松地验证这一点(没有编译器/ vs),但是您可以尝试在再次渲染视图之前以显式方式添加模型错误

if (result.Succeeded)
{
    return RedirectToAction("Index", "Home");
}
else
{
    var error = string.Join( ", ", result.Errors );

    this.ModelState.AddModelError( "Password", error );
}