Attribute自定义特性验证

1. 继承ValidationAttribute写特性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Globalization;

namespace ConsoleApplication3
{
    [AttributeUsage(AttributeTargets.Property)]
    public class RangeAttribute : ValidationAttribute
    {
        public double Min { set; get; }
        public double Max { set; get; }
        public string ErrorMessage{set;get;}
        public RangeAttribute()
            : base()
        { 
        }
        public RangeAttribute(string errorMessage, double min, double max)
            : base(errorMessage)
        {
            this.ErrorMessage = errorMessage;
            this.Min = min;
            this.Max = max;
        }
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, ErrorMessage);
        }

        public override bool IsValid(object value)
        {
            bool flag = true;
            double validValue = Convert.ToDouble(value);
            if (validValue < Min || validValue > Max)
            {
                flag = false;
            }
            return flag;
        }
    }
}

2. 写测试实体Student

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication3
{
    public class Student
    {
        public int ID { set; get; }
        public string Name { set; get; }
        [Range("aaa",1,1000)]
        public string Num { set; get; }
    }
}
3. 写验证接口IValidator<T>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    public interface IValidator<T> where T:class
    {
        bool IsValid(T t);
    }
}

4.实现验证接口Validator<T>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication3
{
    public class Validator<T>:IValidator<T> where T:class
    {
        public bool IsValid(T t)
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }

            Type type = t.GetType();
            PropertyInfo[] properties = type.GetProperties();

            foreach (PropertyInfo property in properties)
            {
                //获取验证特性
                object[] validateContent = property.GetCustomAttributes(typeof(ValidationAttribute), true);

                if (validateContent != null)
                {
                    //获取属性的值
                    object value = property.GetValue(t, null);
                    foreach (ValidationAttribute validateAttribute in validateContent)
                    {
                        if(!validateAttribute.IsValid(value))
			{
				return false;
			}
                    }
                }
            }
            return true;
        }
    }
}

5. 测试

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student();
            student.ID = 1;
            student.Name = "";
            student.Num = "sdfsdfsd";
            Validator<Student> validator = new Validator<Student>();
            Console.WriteLine(validator.IsValid(student).ToString());
            Console.Write("start");
            
            Console.ReadKey();
        }
    }
}




在ASP.NET Core中实现自定义验证特性(Custom Validation Attribute)的步骤如下: 1. 创建一个继承自`ValidationAttribute`的自定义验证特性类,例如: ```csharp public class CustomValidationAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { // 验证逻辑 if (value is string str && str == "abc") { return ValidationResult.Success; } else { return new ValidationResult("必须是 abc"); } } } ``` 其中,`IsValid`方法是用来进行验证的,它接收两个参数:要验证的值和验证上下文。在该方法中,可以编写自定义验证逻辑,并返回`ValidationResult`类型的结果。 2. 在需要验证的模型属性上添加自定义验证特性,例如: ```csharp public class MyModel { [CustomValidation] public string MyProperty { get; set; } } ``` 在这个例子中,`MyProperty`属性上添加了`CustomValidation`特性,表示在验证该属性时,会调用`CustomValidationAttribute`类中的`IsValid`方法。 3. 在控制中进行验证,例如: ```csharp [HttpPost] public IActionResult MyAction([FromBody] MyModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // 其他逻辑 return Ok(); } ``` 在这个例子中,控制的`MyAction`方法接收一个`MyModel`类型的参数,该参数会被自动绑定到请求体中。在方法中,可以通过`ModelState.IsValid`属性来判断模型是否验证通过,如果验证失败,则返回`BadRequest`结果,并将`ModelState`作为响应体返回。 以上就是在ASP.NET Core中实现自定义验证特性的步骤。需要注意的是,自定义验证特性只是一种验证方式,如果需要更复杂的验证逻辑,可以使用`IValidatableObject`接口自定义验证实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值