PostSharp参数验证 - 具有最大长度的可选字符串

时间:2014-07-28 11:46:03

标签: validation parameters postsharp

我正在使用PostSharp 3.1在Web服务上进行参数验证。

我有一个可选的字符串参数,传递时必须少于50个字符。

我目前有[StringLength(50)]这意味着必须传递字符串,string.Empty可以传递,但null不能传递。{/ p>

null对此参数有效。

我需要它的工作方式与[EmailAddress]验证相同 - 如果传递null,则不验证,否则验证是否传递任何字符串。

可以这样做吗?

1 个答案:

答案 0 :(得分:1)

我编写了一个自定义验证属性,如下所示:

using System;

using PostSharp.Aspects;
using PostSharp.Patterns.Contracts;
using PostSharp.Reflection;

public class NullOrStringLengthAttribute : LocationContractAttribute, ILocationValidationAspect<string>
{
    private readonly int maximum;

    public NullOrStringLengthAttribute(int maximum)
    {
        this.maximum = maximum;

        this.ErrorMessage = "The parameter '{0}' must be a string with a maximum length of " + maximum + ".";
    }

    public Exception ValidateValue(string value, string locationName, LocationKind locationKind)
    {
        if (value == null)
        {
            return null;
        }

        return value.Length > this.maximum ? this.CreateArgumentException(value, locationName, locationKind) : null;
    }

}

编辑:已更新,包括最小字符串长度和新的PostSharp 4.x错误消息模式:

using System;

using PostSharp.Aspects;
using PostSharp.Patterns.Contracts;
using PostSharp.Reflection;

public class NullOrStringLengthAttribute : LocationContractAttribute, ILocationValidationAspect<string>
{
    public NullOrStringLengthAttribute(int maximumLength)
    {
        this.ErrorMessage = string.Format("The {{2}} must be null or a string with a maximum length of {0}.", maximumLength);
        this.MaximumLength = maximumLength;
        this.MinimumLength = 0;
    }

    public NullOrStringLengthAttribute(int minimumLength, int maximumLength)
    {
        if (maximumLength != int.MaxValue)
        {
            this.ErrorMessage = string.Format("The {{2}} must be null or a string with length between {0} and {1}.", minimumLength, maximumLength);
        }
        else
        {
            this.ErrorMessage = string.Format("The {{2}} must be null or a string with a minimum length of {0}.", minimumLength);
        }

        this.MaximumLength = maximumLength;
        this.MinimumLength = minimumLength;
    }

    public int MaximumLength { get; private set; }

    public int MinimumLength { get; private set; }

    public Exception ValidateValue(string value, string locationName, LocationKind locationKind)
    {
        if (value == null)
        {
            return null;
        }

        if (value.Length < this.MinimumLength || value.Length > this.MaximumLength)
        {
            return this.CreateArgumentException(value, locationName, locationKind);
        }

        return null;
    }
}