Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建自定义验证属性c#服务器端_C#_Validation_Attributes_Licensing - Fatal编程技术网

创建自定义验证属性c#服务器端

创建自定义验证属性c#服务器端,c#,validation,attributes,licensing,C#,Validation,Attributes,Licensing,我正在尝试创建验证属性以在解决方案中强制许可。 我尝试的方法是使用继承自ValidationAttribute的LicenseValidationAttribute。 主要目标是在调用CreateProject()方法时,如果客户已经达到了他有权获得的项目的限制,这将导致异常抛出。否则,就可以了。 我已经写了一个小程序,但不幸的是它不工作,这意味着它不会抛出异常。 该方案: [AttributeUsage(AttributeTargets.Method)] public class MyVal

我正在尝试创建验证属性以在解决方案中强制许可。 我尝试的方法是使用继承自ValidationAttributeLicenseValidationAttribute。 主要目标是在调用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); ;
        }

    }