Validation .Net核心更改密码验证程序

Validation .Net核心更改密码验证程序,validation,.net-core,react-redux,asp.net-identity,change-password,Validation,.net Core,React Redux,Asp.net Identity,Change Password,我对.NETCore非常陌生,我有一个表单要求用户更改密码。我需要检查后端的验证。本例中的前端发送3个参数(UserID、Password、ConfirmedPWD)。 在类和控制器方面,我在后端需要什么 我的web应用程序是.Net Core 2.1 reactredux模板 谢谢你的帮助 验证: *必须有1个字母 *必须有1个数字 *最少8个,最多16个 CustomPasswordValidator类: public class CustomPasswordValidator {

我对.NETCore非常陌生,我有一个表单要求用户更改密码。我需要检查后端的验证。本例中的前端发送3个参数(UserID、Password、ConfirmedPWD)。 在类和控制器方面,我在后端需要什么

我的web应用程序是.Net Core 2.1 reactredux模板

谢谢你的帮助

验证:

  • *必须有1个字母

  • *必须有1个数字

  • *最少8个,最多16个

  • CustomPasswordValidator类:

    public class CustomPasswordValidator
    
    
    {
        public int RequiredLength { get; set; }
        public CustomPasswordValidator(int length)
        {
    
            RequiredLength = length;
    
        }
    
        public Task<IdentityResult> ValidateAsync(string item)
    
        {
            if (String.IsNullOrEmpty(item) || item.Length < RequiredLength)
    
            {
                List<string> errors = new List<string>() { "Password should be of length {0}" };
                return Task.FromResult(IdentityResult.Failed());
    
            }
    
            string pattern = @"^(?=.*[0-9])(?=.*[!@#$%^&*])[0-9a-zA-Z!@#$%^&*0-9]{10,}$";
            if (!Regex.IsMatch(item, pattern))
    
            {
    
                return Task.FromResult(IdentityResult.Failed());
            }
    
            return Task.FromResult(IdentityResult.Success);
        }
    }
    
    公共类CustomPasswordValidator
    {
    public int RequiredLength{get;set;}
    公共CustomPasswordValidator(整数长度)
    {
    所需长度=长度;
    }
    公共任务ValidateAsync(字符串项)
    {
    if(String.IsNullOrEmpty(item)| | item.Length
    我建议使用FluentValidation库,您可以在其中声明性地指定此类复杂场景

    Install-Package FluentValidation.AspNetCore
    
    你的请求类

    public class ChangePasswordRequest
    {
        public string UserId { get; set; }
        public string Password { get; set; }
        public string ConfirmedPWD { get; set; }
    }
    
    您可以使用fluent validation创建自己的验证类。您还可以添加异常消息

    public class ChangePasswordRequestValidator : AbstractValidator<ChangePasswordRequest>
    {
        public ChangePasswordRequestValidator()
        {
            RuleFor(x => x.Password).Password();
        }
    }
    
    public static class RuleBuilderExtensions
    {
        public static IRuleBuilder<T, string> Password<T>(this IRuleBuilder<T, string> ruleBuilder)
        {
            var options = ruleBuilder
                          .NotEmpty()
                          .NotNull()
                          .MinimumLength(8)
                          .MaximumLength(16)
                          .Matches("^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$").WithMessage("regex error");
    
            return options;
        }
    }
    
    公共类ChangePasswordRequestValidator:AbstractValidator
    {
    公共ChangePasswordRequestValidator()
    {
    RuleFor(x=>x.Password).Password();
    }
    }
    公共静态类RuleBuilderExtensions
    {
    公共静态IRuleBuilder密码(此IRuleBuilder规则生成器)
    {
    var options=ruleBuilder
    .NotEmpty()
    .NotNull()
    .最小长度(8)
    .最大长度(16)
    .Matches(“^(?=.[0-9])(?=.[a-zA-Z])([a-zA-Z0-9]+)$”)。带有消息(“regex错误”);
    返回选项;
    }
    }
    
    一些配置

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
                .AddFluentValidation(fvc =>
                    fvc.RegisterValidatorsFromAssemblyContaining<Startup>());
    }
    
    public void配置服务(IServiceCollection服务)
    {
    services.AddMvc()
    .AddFluentValidation(fvc=>
    fvc.RegisterValidatorsFromAssemblyContaining());
    }
    
    最后,您可以使用ModelState.IsValid检查您的模型

        [HttpPost]
        public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
    
            return Ok();
        }
    
    [HttpPost]
    公共异步任务ChangePassword([FromBody]ChangePasswordRequest请求)
    {
    如果(!ModelState.IsValid)
    {
    返回请求();
    }
    返回Ok();
    }
    
    我建议使用FluentValidation库,您可以在其中声明性地指定此类复杂场景

    Install-Package FluentValidation.AspNetCore
    
    你的请求类

    public class ChangePasswordRequest
    {
        public string UserId { get; set; }
        public string Password { get; set; }
        public string ConfirmedPWD { get; set; }
    }
    
    您可以使用fluent validation创建自己的验证类。您还可以添加异常消息

    public class ChangePasswordRequestValidator : AbstractValidator<ChangePasswordRequest>
    {
        public ChangePasswordRequestValidator()
        {
            RuleFor(x => x.Password).Password();
        }
    }
    
    public static class RuleBuilderExtensions
    {
        public static IRuleBuilder<T, string> Password<T>(this IRuleBuilder<T, string> ruleBuilder)
        {
            var options = ruleBuilder
                          .NotEmpty()
                          .NotNull()
                          .MinimumLength(8)
                          .MaximumLength(16)
                          .Matches("^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$").WithMessage("regex error");
    
            return options;
        }
    }
    
    公共类ChangePasswordRequestValidator:AbstractValidator
    {
    公共ChangePasswordRequestValidator()
    {
    RuleFor(x=>x.Password).Password();
    }
    }
    公共静态类RuleBuilderExtensions
    {
    公共静态IRuleBuilder密码(此IRuleBuilder规则生成器)
    {
    var options=ruleBuilder
    .NotEmpty()
    .NotNull()
    .最小长度(8)
    .最大长度(16)
    .Matches(“^(?=.[0-9])(?=.[a-zA-Z])([a-zA-Z0-9]+)$”)。带有消息(“regex错误”);
    返回选项;
    }
    }
    
    一些配置

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
                .AddFluentValidation(fvc =>
                    fvc.RegisterValidatorsFromAssemblyContaining<Startup>());
    }
    
    public void配置服务(IServiceCollection服务)
    {
    services.AddMvc()
    .AddFluentValidation(fvc=>
    fvc.RegisterValidatorsFromAssemblyContaining());
    }
    
    最后,您可以使用ModelState.IsValid检查您的模型

        [HttpPost]
        public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
    
            return Ok();
        }
    
    [HttpPost]
    公共异步任务ChangePassword([FromBody]ChangePasswordRequest请求)
    {
    如果(!ModelState.IsValid)
    {
    返回请求();
    }
    返回Ok();
    }
    
    当您使用.net core时,您不必像

    [HttpPost]
        public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
    
            return Ok();
        }
    
    [HttpPost]
    公共异步任务ChangePassword([FromBody]ChangePasswordRequest请求)
    {
    如果(!ModelState.IsValid)
    {
    返回请求();
    }
    返回Ok();
    }
    

    控制器上的[ApiController]注释将自动为您执行modelstate验证。如果您觉得合适,请阅读并使用它。

    当您使用.net core时,您不必像这样显式地检查ModelState

    [HttpPost]
        public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
    
            return Ok();
        }
    
    [HttpPost]
    公共异步任务ChangePassword([FromBody]ChangePasswordRequest请求)
    {
    如果(!ModelState.IsValid)
    {
    返回请求();
    }
    返回Ok();
    }
    

    控制器上的[ApiController]注释将自动为您执行modelstate验证。阅读一下,如果你觉得合适就使用它。

    hi,您用来验证密码的属性是什么?我认为实现这一点的一个好方法是在助手类中编写一个静态方法,根据您希望的检查验证密码,然后在某些服务中调用此验证方法,而不是直接在控制器中调用。嗨,您用来验证密码的属性是什么?我认为实现这一点的一个好方法是在助手类中编写一个静态方法,根据您希望的检查验证密码,然后在某些服务中调用此验证方法,而不是直接在控制器中调用。