如何将自定义验证应用到ASP中的角色提供程序中.asp.net MVC5净的身份
本文关键字:asp 程序 net MVC5 身份 角色 应用 验证 自定义 ASP | 更新日期: 2023-09-27 18:19:10
我已经用新的属性修改了UserRole实体。我需要验证用户登录并根据这些属性生成基于角色的菜单。
public class ApplicationUserRole : IdentityUserRole
{
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationUserRole"/> class.
/// </summary>
public ApplicationUserRole()
: base()
{
this.ValidFrom = DateTime.Now;
this.ValidTo = DateTime.Now;
}
/// <summary>
/// Gets or sets the valid from.
/// </summary>
/// <value>The valid from.</value>
public virtual DateTime? ValidFrom { get; set; }
/// <summary>
/// Gets or sets the valid to.
/// </summary>
/// <value>The valid to.</value>
public virtual DateTime? ValidTo { get; set; }
}
如果登录日期不在有效日期范围内,则需要显示用户登录过期消息,如果分配了多个角色并且一个角色过期,则需要隐藏菜单列表中的菜单项
您可以使用自定义ValidationAttribute
using System.ComponentModel.DataAnnotations;
public class ValidDates : ValidationAttribute
{
protected override ValidationResult
IsValid(object value, ValidationContext validationContext)
{
var model = (Models.Employee)validationContext.ObjectInstance;
DateTime _validFrom = Convert.ToDateTime(model.validFrom);
DateTime _validTo = Convert.ToDateTime(model.ValidTo);
if(validation condition is true)
return ValidationResult.Success;
else
return ValidationResult.failure;
}
}
并用ValidDates属性装饰你的ApplicationUserRole类。
[ValidDates]
public class ApplicationUserRole : IdentityUserRole
{ //other class implementation }