2016-04-17 35 views
3

我试图创建验证属性实施许可在我的解决方案。 我试图做到这一点的方式是通过LicenseValidationAttributeValidationAttribute继承使用。 的主要目标是当的createProject()方法被调用,如果客户已经达到了他的标题是项目,这将导致异常抛出了极限。否则,这将是确定的流动。 我已经写一个小程序,但遗憾的是它不工作,意味着它不抛出异常。 程序:创建自定义属性验证,C#服务器端

[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); ; 
     } 

    } 

谢谢!

回答

0

添加的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); ; 
     } 

    } 
相关问题