为什么modelstate.isvalid点击登录按钮? [英] Why modelstate.isvalid clicking on the login button?

查看:78
本文介绍了为什么modelstate.isvalid点击登录按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的用户型号:



this is my Users Model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace Models
{
    public class Users
    {
        [Key]
        public int UserID { get; set; }

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

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

        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email Address")]
        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; }

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

        public string PhoneNumber { get; set; }

        [DataType(DataType.DateTime)]
        [Required]
        public DateTime RegistrationDate { get; set; }

       
       
    }







这个是我的登录操作:






This is my Login action:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Users user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var errors = ModelState.Values.SelectMany(v => v.Errors);
                    CarDBContext db = new CarDBContext();
                    var getUser = db.Users.Single(p => p.Email == user.Email && p.Password == user.Password);
                    if (getUser != null)
                    {
                        Session["Usr_ID"] = user.UserID.ToString();
                        Session["Email"] = user.Email.ToString();
                        Session["UserName"] = user.FirstName.ToString() + " " + user.LastName.ToString();
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Username or Password does not match.");
                    }
                }
            }
            catch (Exception ex)
            {
                return View("Error", new HandleErrorInfo(ex, "", ""));
            }

            return View();
        }





这是我的创建用户操作正常工作:



This is my Create user action that works properly:

[HttpPost]
     public ActionResult CreateUser(Users user)
     {

           if (ModelState.IsValid)
         {
             bool Success = IsUserEmailExist(user.Email);

             if (Success == false)
             {
                 db.Users.Add(user);
                 db.SaveChanges();
                 return RedirectToAction("Index","Home");
             }

             else
             {
                 string err = "The user already exists.";
                 ViewBag.ErrMessage = err;
                 return View();
             }
         }
         return View(user);
     }





我尝试过:



我不知道为什么我的创建用户工作正常但我的登录没有。登录actionresult中的Modelstate.isvalid始终为false。

如何使用ViewModel编写它?



What I have tried:

I dont know why my create user is working properly but my login doesnt. Modelstate.isvalid in the login actionresult always is false.
How can I write it with ViewModel?

推荐答案

您收到验证错误因为用户在登录时没有从 Users 类中输入每个字段。他们只输入他们的电子邮件和密码。其他必填字段将为空白。



为登录操作创建一个视图模型:

You're getting validation errors because the user isn't entering every single field from the Users class when they log in. They're only entering their email and password. The other required fields will be blank.

Create a view-model for the login action:
public class LoginViewModel
{
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email Address")]
    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; }
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel user)
{
   ...
}



HOWEVER ,正如我所提到的在评论中,您应永远以纯文本格式存储密码。只存储密码的盐渍哈希,每个记录使用一个唯一的盐。



简单安全密码验证说明 [ ^ ]

Salted Password Hashing - 正确行事 [ ^ ]



你为什么要重新发明轮子? ASP.NET内置了几个非常好的身份验证系统 - 例如, ASP.NET身份 [ ^ ]。


HOWEVER, as I mentioned in the comments, you should NEVER store passwords in plain text. Only ever store a salted hash of the password, using a unique salt for each record.

Secure Password Authentication Explained Simply[^]
Salted Password Hashing - Doing it Right[^]

And why are you re-inventing the wheel? ASP.NET has several perfectly good authentication systems built-in - for example, ASP.NET Identity[^].




问题出在您的用户模型中,这意味着当您提交登录按钮时模型验证验证用户模型中的所有验证字段,但是您只传递用户名和密码。

因此您需要为登录创建新模型。



步骤-1)

公共类LoginViewModel

{

[必填]

[ DataType(DataType.EmailAddress)]

[显示(姓名=电子邮件地址)]

公共字符串电子邮件{get;组; } $ / $


[必填]

[StringLength(100,ErrorMessage ={0}长度必须至少为{2}个字符。 ,MinimumLength = 6)]

[DataType(DataType.Password)]

[显示(名称=密码)]

public string密码{get;组; }

}



步骤2)



[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult Login(LoginViewModel用户)

{

if(ModelState.IsValid)

{

....

}

}



我希望这对你有用

Happy Coding =:)
Hi,
The problem is in the your Users model that means when you submit the login button model validation validate all the validation field that are in User model but you are passing only user name and password.
So you need to create new model for Login.

Step-1)
public class LoginViewModel
{
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email Address")]
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; }
}

Step-2)

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel user)
{
if (ModelState.IsValid)
{
....
}
}

I hope this is working for you
Happy Coding=:)


这篇关于为什么modelstate.isvalid点击登录按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆