Best way to check WCF and WebService method parameter values

I am going to write a validation component to use it for different projects. I am not very familiar with any validation frames such as Enterprise Library VAB , Fluent , CuttingEdge.Conditions and many others, however I don’t have time to work with all of them to see what is best for my purpose.

I want this component to provide me with two different functions:

First , I want to have some validators, such as EmailValidator, StringLengthValidator, MyCustomValidator, etc., which I can use them whenever I want in the code, for example below:

public class EmailValidator : RegexValidator // or StringValidator or whatever!
{
    public EmailValidator() : base("emailRegexHere")
    {
    }
public bool override DoValidate(string value)
    {
        return base.DoValidate(value);
    }
}
...

public void MyMethod(string email)
{
    EmailValidator validator = new EmailValidator();
    if(!validator.Validate(email))
        throw new NotValidatedException("email is invalid.");
    ...
}

, , - DataAnnotations , , - . , , - , PostSharp, , (OnMethodEntry). Logging with Postsharp, .

Microsoft IParameterInspector WCF, 2 BeforCall AfterCall, , WCF.

, WCF WebService :

[System.Web.Script.Services.ScriptService]
public class MyServiceClass : System.Web.Services.WebService
{
    [Aspects.Validate]
    [WebMethod(EnableSession = true)]
    public string SubmitComment([Validation.Required]string content,[Validation.Guid] string userId,[Validation.Required] [Validation.Name]string name, [Validation.Email]string email, string ipAddress)
    {
        ...
    }
}

: , , . , Validation. * , ValidateParam (typeof (EmailValidator))?

+5
1

, PostSharp . OnMethodBoundaryAspect MethodInterceptionAspect, ( , , ) (, ).

OnMethodBoundaryAspect, MethodExecutionArgs. args.Method ( a MethodBase, System.Reflection). GetParameters(), ParameterInfo. ParameterInfo Attributes.

, , ( , ). args.Arguments .

(psuedo):

public interface IValidator
{
    void Validate(object value);
}
public class ValidationEmailAttribute : Attribute, IValidator
{
    public Validate(string emailAddress)
    {
        // throw exception or whatever if invalid
    }
}

public class ValidateParametersAspect : OnMethodBoundaryAspect
{
    public override OnEntry(args)
    {
        foreach(i = 0 to args.Method.GetParameters().Count)
        {
            var parameter = args.Method.GetParameters()[i];
            var argument = args.Argument[i]; // get the corresponding argument value
            foreach(attribute in parameter.Attributes)
            {
                var attributeInstance = Activator.CreateType(attribute.Type);
                var validator = (IValidator)attributeInstance;
                validator.Validate(argument);
            }
        }
     }
}

public class MyClass
{
    [ValidateParametersAspect]
    public void SaveEmail([ValidationEmail] string email)
    {
        // ...
    }
}

: , .

, , .

+3

All Articles