如何使用ASP.Net Identity将自定义验证应用于ASP.NET MVC5中的角色提供程序?

时间:2015-10-26 07:54:59

标签: c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity

我已使用新属性修改了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; }

 }

如果有效日期范围内不存在登录日期,则需要显示用户登录过期消息,如果分配了多个角色且过期,则需要在菜单列表中隐藏这些菜单项。

1 个答案:

答案 0 :(得分:1)

您可以使用自定义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  }

了解详情MVC custom attribute validation