如何从actionfilter中的属性获取值

时间:2012-12-16 17:13:30

标签: c# asp.net-mvc-3 attributes actionfilterattribute

标题看起来有点奇怪,对不起。

我是Asp.net MVC 3的新手。我想为我的一个属性创建一个属性,该属性的名称是国家身份号码。

    public class IdentityNumberControl : ActionFilterAttribute
{
    public string WrongIdentityNumber { get; set; }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        if(??? )
        {
            filterContext.HttpContext.Response.Write(WrongIdentityNumber);
            return;
        }
        base.OnActionExecuting(filterContext);
    }
}

我的会员班在这里

 public class Member
{
    public int ID { get; set; }
    [Required(ErrorMessage = "You have to enter your name")]
    [StringLength(50, ErrorMessage  ="Your name length can not be less than{2} more than {1} ", MinimumLength = 3)]
    [Display("Name :")]
    public string Name { get; set; }

    [Required(ErrorMessage = "You have to enter your surname")]
    [StringLength(40, ErrorMessage = "Your surname length can not be less than{2} more than {1} ", MinimumLength = 2)]
    [Display("Surname :")]
    public string SurName { get; set; }

    [Required(ErrorMessage = "You have to enter your password")]
    [StringLength(20, ErrorMessage = "Your name lengt can not be less than{2} more than {1} ", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display("Password :")]
    public string Password { get; set; }
    public string PasswordSalt { get; set; }

    [IdentityNumberControl(WrongIdentityNumber = "It is not a valid identity number")]
    public double IdentityNumber { get; set; }

}

所以我想检查一下identitynumber是否为真(我有一个计算方法来确认) 我知道我必须在IdentityNumberControl类中编写代码。但我不知道如何在OnActionExecuting方法中获得identitynumber的值。

我希望我解释一下我的问题

1 个答案:

答案 0 :(得分:0)

这是我的解决方案

public class IdentityNumberAttribute : ValidationAttribute
{
    private string WrongIdentityNumber;

    public IdentityNumberAttribute(string message)
    {
        WrongIdentityNumber = message;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {

        string identityNumber = value.ToString();

        if (identityNumber.Length != 11)
            return new ValidationResult(WrongIdentityNumber);

        int sum = 0;


        for (int i = 0; i < identityNumber.Length - 1; i++)
        {
            sum += Convert.ToInt32(identityNumber[i].ToString());
        }

        return sum.ToString()[1] == identityNumber[10]
                   ? ValidationResult.Success
                   : new ValidationResult(WrongIdentityNumber);
    }
}

如果有效土耳其国民身份证号码,则计算

你可以像这样使用这个属性

    [IdentityNumber("It is not a valid identity number")]
    [Required(ErrorMessage = "You have to enter your identity number")]
    [DisplayName("National Identity Number:")]
    public string IdentityNumber { get; set; }