创建自定义验证属性 c# 服务器端
Create custom validation attributes c# server side
我正在尝试创建验证属性以在我的解决方案中实施许可。
我尝试这样做的方法是使用继承自 ValidationAttribute 的 LicenseValidationAttribute。
主要目标是在调用 CreateProject() 方法时,如果客户已经达到他有权获得的项目限制,将导致异常抛出。否则,那将是确定的流程。
我写了一个小程序,但不幸的是它不起作用,这意味着它不会抛出异常。
节目:
[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); ;
}
}
我正在尝试创建验证属性以在我的解决方案中实施许可。 我尝试这样做的方法是使用继承自 ValidationAttribute 的 LicenseValidationAttribute。 主要目标是在调用 CreateProject() 方法时,如果客户已经达到他有权获得的项目限制,将导致异常抛出。否则,那将是确定的流程。 我写了一个小程序,但不幸的是它不起作用,这意味着它不会抛出异常。 节目:
[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); ;
}
}