【问题标题】:ASP.NET Core MVC : use remote input validationASP.NET Core MVC:使用远程输入验证
【发布时间】:2021-04-20 04:06:54
【问题描述】:

编辑 1:包括与此相关的完整代码,而不仅仅是一部分。

我正在尝试为我的应用程序的管理员角色创建用户名输入验证。 我将从 SQL server 中的表开始。

Employee table columns in SQL server has [ROWID],[ID],[LAST_NAME],[FIRST_NAME]...

员工数据库模型

public class EmployeeModel
    {
        public int RowID { get; set; }
        [Key]
        public int ID { get; set; }
        public string First_Name { get; set; }
        public string Last_Name { get; set; }
    }

数据库上下文

public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext (DbContextOptions<ApplicationDbContext> options) : base(options)
        { 
        }

        public DbSet<WorkOrderModel> WorkOrder { get; set; }
        public DbSet<CommentModel> Comment { get; set; }
        public DbSet<PostModel> Post { get; set; }
        public DbSet<ReplyModel> Reply { get; set; }
        public DbSet<ApplicationUser> ApplicationUser { get; set; }
        public DbSet<EmployeeModel> Employee { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder); //This is necessary if class is IdentityDbContext instead of DbContext
            modelBuilder.Entity<WorkOrderModel>().HasKey(c => new { c.Type, c.Base_ID, c.Lot_ID, c.Split_ID, c.Sub_ID });
        }
    }

我的 InputValidation 控制器是其中只有远程验证逻辑的控制器。 我正在尝试构建一个逻辑来验证用户是否在仅使用 [ID] 和 [FIRST_NAME] 的表“员工”中。

我的原始代码如下。

if (_dbContext.Employee.Any(n => (n.First_Name + "." + n.ID.ToString().PadLeft(3, '0')) == userName) != true)
            {
                return Json(true);
            }

            return Json($"Employee does not exist.");

然后根据 Tisa 在回复中的建议更改为以下内容。

public class InputValidationController : Controller
    {
        private readonly ApplicationDbContext _dbContext;

        public InputValidationController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [AcceptVerbs("GET", "POST")]
        public IActionResult IdVerification(string userName)
        {
            var allUserList = (from u in _dbContext.Employee
                               select new
                               {
                                   Name = u.First_Name + "." + u.ID.ToString().PadLeft(3, '0')
                               })
                               .ToList().Where(x => x.Name == userName);

            if (allUserList != null)
            {
                return Json(true);
            }
            return Json($"Employee does not exist.");
        }
    }

输入类所在的PageModel。

public class ResetPasswordModel : PageModel
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly ILogger<ResetPasswordModel> _logger;


        public ResetPasswordModel(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<ResetPasswordModel> logger)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        [TempData]
        public string StatusMessage { get; set; }

        public class InputModel
        {
            [Required]
            [Display(Name = "User Name [ First Name.### (Employee number) ]")]
            [Remote(action: "IdVerification", controller: "InputValidation")]
            public string UserName { get; set; }

            [Required]
            [StringLength(20, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
            [DataType(DataType.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; }

            //public string Code { get; set; }
        }
    ...
    }

最后是查看页面。 SQL_Web_App 是项目的名称,具有 UserRoles 类。

@page
@model ResetPasswordModel
@using SQL_Web_App

@{
    ViewData["Title"] = "Reset password";
}

@if (User.IsInRole(UserRoles.AdminRole))
{
    <h1>@ViewData["Title"]</h1>
        <h4>Reset password for a user.</h4>
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Input.UserName"></label>
                <input asp-for="Input.UserName" class="form-control" />
                <span asp-validation-for="Input.UserName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.Password"></label>
                <input asp-for="Input.Password" class="form-control" />
                <span asp-validation-for="Input.Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.ConfirmPassword"></label>
                <input asp-for="Input.ConfirmPassword" class="form-control" />
                <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-primary">Reset</button>
            </form>
        </div>
    </div>
}

我在此编辑之前的声明 1

As you can see under the display of the `InputModel` the user name is "FirstName.EmployeeNumber", I am trying to match that input to `_dbContext.Employee.Any(n => n.First_Name + "." + n.ID.ToString().PadLeft(3, '0')` but I do not get any result for both != and ==.

现在我在下面尝试了 == 和 != 结果在任何情况下都始终不为空。

if (allUserList != null)
{
    Json(true);
}
return Json($"Employee does not exist.");

请帮我看看我做错了什么。

谢谢。

random name input but no validation message

【问题讨论】:

    标签: asp.net-core-mvc remote-validation


    【解决方案1】:

    你可以把逻辑改成这样:

    要在代码中获取名称,您应该使用模型接受它,然后获取

    用户名属性。

    public IActionResult IdVerification(InputModel input)
        {
            var username=input.UserName;
            var allUserList = (from u in _dbcontext.Employee
                               select new
                               {
                                   Name = u.First_Name + "." + u.ID.ToString().PadLeft(3, '0')
                               })
                               .ToList();
    
            if (allUserList[0].Name==userName)
            {
                return Json(true);
            }
            return Json($"Employee does not exist.");
        }
    

    【讨论】:

    • 感谢您的意见!但我发现脚本中的 allUserList 是 IEnumerable 并且始终不为空。
    • @NamelessCosmicDust 什么意思?如果相关名称不存在,则为空。能否请您用代码分享您的详细需求?
    • 嗯好的,我将分享所有内容,而不仅仅是上面的部分代码。
    • 我编辑了我的帖子以包含我拥有的所有代码。
    • @NamelessCosmicDust 我已经编辑了我的答案,它会解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 2010-09-14
    相关资源
    最近更新 更多