创建自定义验证属性c#服务器端
我正在尝试创建验证属性以在解决方案中强制许可。 我尝试的方法是使用继承自ValidationAttribute的LicenseValidationAttribute。 主要目标是在调用CreateProject()方法时,如果客户已经达到了他有权获得的项目的限制,这将导致异常抛出。否则,就可以了。 我已经写了一个小程序,但不幸的是它不工作,这意味着它不会抛出异常。 该方案:创建自定义验证属性c#服务器端,c#,validation,attributes,licensing,C#,Validation,Attributes,Licensing,我正在尝试创建验证属性以在解决方案中强制许可。 我尝试的方法是使用继承自ValidationAttribute的LicenseValidationAttribute。 主要目标是在调用CreateProject()方法时,如果客户已经达到了他有权获得的项目的限制,这将导致异常抛出。否则,就可以了。 我已经写了一个小程序,但不幸的是它不工作,这意味着它不会抛出异常。 该方案: [AttributeUsage(AttributeTargets.Method)] public class MyVal
[AttributeUsage(AttributeTargets.Method)]
public class MyValidationAttribute : ValidationAttribute
{
public MyValidationAttribute()
{
}
public override bool IsValid(object value)
{
int id = (int)value;
if (id > 0)
return true;
throw new Exception("Error");
}
}
public class Service
{
[MyValidation]
public bool GetService(int id)
{
if (id > 100)
{
return true;
}
return false;
}
}
static void Main(string[] args)
{
try
{
Service service = new Service();
service.GetService(-8);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
}
谢谢 添加System.reflection的
GetCustomAttributes
方法调用后,它可以工作:
static void Main(string[] args)
{
try
{
Service service = new Service();
service.GetService(-8);
service.GetType().GetCustomAttributes(false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
}