基于特性的服务端验证

最近在做一个项目,某网站的会员系统。感觉在每个页面做服务端的验证非常烦锁。所以写了一个用方法用对象特性来实现功能。

首先定义Attribute类

namespace DataBase
{
    /// <summary>
    /// Attribute类
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class DataFieldAttribute : Attribute
    {
        string _columnName;
        bool _IsEmpty = true;

        public DataFieldAttribute(string columnName)
        {
            this._columnName = columnName;
        }

        /// <summary>
        /// 是否允许为空
        /// </summary>
        public bool IsEmpty
        {
            get { return this._IsEmpty; }
            set { this._IsEmpty = value; }
        }
    }
}

对象特性的声明

        /// <summary>
        /// 关键字
        /// </summary>
        [DataBase.DataField("keyword", IsEmpty = false)]
        public string KeyWord
        {
            get
            {
                return _keyword;
            }
            set
            {
                _keyword = value;
            }
        }

写入基类的验证

protected string DataVerificationForPage(object o, out bool reValue)
    {
        reValue = true;
        string str = "";
        Type oType = o.GetType();
        PropertyInfo[] proInfos = oType.GetProperties();
        object fieldValue = null;
        DataFieldAttribute attribute;
        foreach (PropertyInfo proInfo in proInfos)
        {

              if (proInfo.IsDefined(typeof(DataFieldAttribute), false))
              {

                attribute = (DataFieldAttribute)Attribute.GetCustomAttribute(proInfo, typeof(DataFieldAttribute));//判断是否允许为空
                if (!attribute.IsEmpty)
                {if (string.IsNullOrEmpty(proInfo.GetValue(o, null).ToString()))
                    {
                        reValue = false;
                        str += "不允许为空!";
                        return str;
                    }
                }
            }
        }

        return "";
    }

最后面页面调用

RssModel m = GetData();

bool reValue;
string str = this.DataVerificationForPage(m, out reValue);
if (!reValue)
{
     Js.Text = "alert('" + str + "');";
     return;
}

注:上面的代码只是实现了服务端验证数据不能为空的情况,还有更多验证可以通过增加特性属性来灵活处理。可以省去每个页面都要去做的验证操作(只需要在实例化对象的时候加注对象属性的特性即可),而且不容易遗漏。在服务器性能允许的时候可以考虑用此方法来实现。

posted @ 2012-06-13 11:51  蹩脚的舞步  阅读(204)  评论(0编辑  收藏  举报