验证消息未在登录页面上显示

时间:2022-05-31 19:20:39

I have a controller called Account Controller which houses my login function. The problem I am having its going straight to the index page instead of displaying the Model Error for invalid login.

我有一个名为Account Controller的控制器,它包含我的登录功能。问题是我直接进入索引页面而不是显示无效登录的模型错误。

In aps.net web forms their used to be a validation group and a validationsummary is the same required here

在aps.net Web表单中,他们曾经是一个验证组,验证组与此处相同

[HttpPost]
public async Task<IActionResult> Login(string email, string password, bool rememberMe)
{
        var user = await _userManager.FindByEmailAsync(email);
        if (user == null)
        {
            ModelState.AddModelError(string.Empty, "Invalid login");
            return View();
        }
        if (!user.EmailConfirmed)
        {
            ModelState.AddModelError(string.Empty, "Confirm your email first");
            return View();
        }

        var passwordSignInResult = await _signInManager.PasswordSignInAsync(user, password, isPersistent: rememberMe, lockoutOnFailure: false);



        if (!passwordSignInResult.Succeeded)
        {
            await _userManager.AccessFailedAsync(user);
            ModelState.AddModelError(string.Empty, "Invalid login");
            return View();
        }

        return Redirect("~/");
    }

Login Page

登录页面

<form asp-controller="Account" asp-action="Login" method="post">

    <div class="form-group has-feedback">
        <input type="email" class="form-control" name="email" id="email" placeholder="Email">
        <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
    </div>
    <div class="form-group has-feedback">
        <input type="password" class="form-control" name="password" id="password" placeholder="Password">
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
    </div>
    <div class="row">
        <div class="col-xs-8">
            <div class="checkbox icheck">
                <label>
                    <input type="checkbox" name="rememberMe" value="true"> Remember Me
                    <input type="hidden" name="rememberMe" value="false" />

                </label>
            </div>
        </div>
        <!-- /.col -->
        <div class="col-xs-4">
            <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
        </div>
        <!-- /.col -->
    </div>
    </form> 

My Startup.cs Configure in case anything is missing.

我的Startup.cs配置以防万一丢失。

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

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


    }

1 个解决方案

#1


1  

Tried your code and it works fine and shows Index page only when no errors were added to ModelState.

尝试了你的代码,它工作正常,只有在没有错误添加到ModelState时显示索引页面。

Validationsummary is still present in ASP.NET Core you can use it like below.

Validationsummary仍然存在于ASP.NET Core中,您可以像下面一样使用它。

<form asp-controller="Account" asp-action="Login" method="post">

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group has-feedback">
            <input type="email" class="form-control" name="email" id="email" placeholder="Email">
        <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
    </div>
    ...
    </form>

When I used this code, errors displayed on page without any issues. 验证消息未在登录页面上显示

当我使用此代码时,页面上显示的错误没有任何问题。

But as suggestion you can improve your code a bit and instead of many return View(); in code just use this code in the end of the method before return Redirect("~/")

但作为建议你可以改进你的代码,而不是很多返回View();在代码中只需在方法结束时使用此代码,然后返回Redirect(“〜/”)

    if (!ModelState.IsValid)
        return View();

UPDATE: There is the full code of Login method.

更新:有完整的Login方法代码。

[HttpPost]
public async Task<IActionResult> Login(string email, string password, bool rememberMe)
{
    IdentityUser user = await _userManager.FindByEmailAsync(email);
    if (user == null)
    {
        ModelState.AddModelError(string.Empty, "Invalid login");
        return View();//this should be kept because if user NULL, PasswordSignInAsync will generate exception
    }
    if (!user.EmailConfirmed)
    {
        ModelState.AddModelError(string.Empty, "Confirm your email first");
    }

    var passwordSignInResult = await _signInManager.PasswordSignInAsync(user, password, isPersistent: rememberMe, lockoutOnFailure: false);

    if (!passwordSignInResult.Succeeded)
    {
        await _userManager.AccessFailedAsync(user);
        ModelState.AddModelError(string.Empty, "Invalid login");
    }

    if (!ModelState.IsValid)
        return View();

    return Redirect("~/");
}

UPDATE2: The easiest way, in my opinion, to handle empty emails in this case is just using required attribute in your View for email field like below.

UPDATE2:在我看来,在这种情况下处理空电子邮件的最简单方法就是在View for email字段中使用必需的属性,如下所示。

<input required type="email" class="form-control" name="email" id="email" placeholder="Email">

This required attribute specifies that the user must fill in a value before submitting a form, without entering value for email you will not be able to submit form, therefore you will not get exception. You can read more about required attribute here and plus another link about form validation(see required attribute section).

此必需属性指定用户必须在提交表单之前填写值,而不输入您无法提交表单的电子邮件的值,因此您不会获得例外。您可以在此处阅读有关所需属性的更多信息以及有关表单验证的其他链接(请参阅必需属性部分)。

#1


1  

Tried your code and it works fine and shows Index page only when no errors were added to ModelState.

尝试了你的代码,它工作正常,只有在没有错误添加到ModelState时显示索引页面。

Validationsummary is still present in ASP.NET Core you can use it like below.

Validationsummary仍然存在于ASP.NET Core中,您可以像下面一样使用它。

<form asp-controller="Account" asp-action="Login" method="post">

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group has-feedback">
            <input type="email" class="form-control" name="email" id="email" placeholder="Email">
        <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
    </div>
    ...
    </form>

When I used this code, errors displayed on page without any issues. 验证消息未在登录页面上显示

当我使用此代码时,页面上显示的错误没有任何问题。

But as suggestion you can improve your code a bit and instead of many return View(); in code just use this code in the end of the method before return Redirect("~/")

但作为建议你可以改进你的代码,而不是很多返回View();在代码中只需在方法结束时使用此代码,然后返回Redirect(“〜/”)

    if (!ModelState.IsValid)
        return View();

UPDATE: There is the full code of Login method.

更新:有完整的Login方法代码。

[HttpPost]
public async Task<IActionResult> Login(string email, string password, bool rememberMe)
{
    IdentityUser user = await _userManager.FindByEmailAsync(email);
    if (user == null)
    {
        ModelState.AddModelError(string.Empty, "Invalid login");
        return View();//this should be kept because if user NULL, PasswordSignInAsync will generate exception
    }
    if (!user.EmailConfirmed)
    {
        ModelState.AddModelError(string.Empty, "Confirm your email first");
    }

    var passwordSignInResult = await _signInManager.PasswordSignInAsync(user, password, isPersistent: rememberMe, lockoutOnFailure: false);

    if (!passwordSignInResult.Succeeded)
    {
        await _userManager.AccessFailedAsync(user);
        ModelState.AddModelError(string.Empty, "Invalid login");
    }

    if (!ModelState.IsValid)
        return View();

    return Redirect("~/");
}

UPDATE2: The easiest way, in my opinion, to handle empty emails in this case is just using required attribute in your View for email field like below.

UPDATE2:在我看来,在这种情况下处理空电子邮件的最简单方法就是在View for email字段中使用必需的属性,如下所示。

<input required type="email" class="form-control" name="email" id="email" placeholder="Email">

This required attribute specifies that the user must fill in a value before submitting a form, without entering value for email you will not be able to submit form, therefore you will not get exception. You can read more about required attribute here and plus another link about form validation(see required attribute section).

此必需属性指定用户必须在提交表单之前填写值,而不输入您无法提交表单的电子邮件的值,因此您不会获得例外。您可以在此处阅读有关所需属性的更多信息以及有关表单验证的其他链接(请参阅必需属性部分)。