一行代码搞定你的QueryString!(原创)

Web开发做得多了,总觉得是体力活,于是搞些代码让自己脱离无聊的Coding吧(是脱离“无聊的”Coding,不是脱离无聊的“Coding”)。
 

初级阶段

为每个QueryString写转换的代码,针对不同的类型,进行转换和错误处理。
 

中级阶段

写了一个函数,专门做转换(1.1里写的):

  /// <summary>
  
/// Convert query string to parameter.
  
/// </summary>
  
/// <param name="name">Name of query string</param>
  
/// <param name="defaultValue">Default value of query string</param>
  
/// <param name="isRequired">If the query string is required</param>
  private object ConvertParameter(string name, object defaultValue, bool isRequired)

高级阶段

昨天写的,第一次发文,大家拍砖吧:
 
主要是用了Attribute和反射的思想,首先给变量设置HttpQueryString的属性,绑定上相应的QueryString,然后由Page基类来读取相应的QueryString信息。

属性这么写(HttpQueryStringAttribute.cs):

using System;

namespace GooKuu.Framework.Web
{

    
/// <summary>
    
/// Specifies a field for a query string. 
    
/// </summary>
    [AttributeUsage(AttributeTargets.Field)]
    
public sealed class HttpQueryStringAttribute : Attribute
    {
        
private string _name;
        
private object _defaultValue;
        
private bool _isRequired;

        
/// <summary>
        
/// Constructor. The query string must be provided.
        
/// </summary>
        
/// <param name="name">Name of the query string</param>
        public HttpQueryStringAttribute(string name)
        {
            _name 
= name;
            _defaultValue 
= null;
            _isRequired 
= true;
        }

        
/// <summary>
        
/// Constructor. If the query string is not be provided, using the default value.
        
/// </summary>
        
/// <param name="name">Name of the query string</param>
        
/// <param name="defaultValue">Default value of the query string which is not provided</param>
        public HttpQueryStringAttribute(string name, object defaultValue)
        {
            _name 
= name;
            _defaultValue 
= defaultValue;
            _isRequired 
= false;
        }

        
/// <summary>
        
/// Name of the query string.
        
/// </summary>
        public string Name
        {
            
get { return _name; }
        }

        
/// <summary>
        
/// Default value of the query string which is not provided.
        
/// </summary>
        public object DefaultValue
        {
            
get { return _defaultValue; }
        }

        
/// <summary>
        
/// Indicates if the query string must be provided.
        
/// </summary>
        public bool IsRequired
        {
            
get { return _isRequired; }
        }
    }
}

页面基类是这样的(PageBase.cs):

using System;
using System.Reflection;
using System.Web;
using System.Web.UI;

namespace GooKuu.Framework.Web
{
    
/// <summary>
    
/// Base class of all pages.
    
/// </summary>
    public class PageBase : Page
    {
        
/// <summary>
        
/// Override OnLoad method of base class.
        
/// </summary>
        
/// <param name="e"></param>
        protected override void OnLoad(System.EventArgs e)
        {
            ParameterInitialize();
            
base.OnLoad(e);
        }

        
/// <summary>
        
/// Initialize parameters according to query strings.
        
/// </summary>
        private void ParameterInitialize()
        {
            
// Get Type of current page class.
            Type type = this.GetType();

            
// Get all fields of current page class.
            FieldInfo[] fields = type.GetFields();

            
foreach (FieldInfo field in fields)
            {
                
// Get HttpQueryStringAttribute of current field.
                HttpQueryStringAttribute attribute = (HttpQueryStringAttribute)Attribute.GetCustomAttribute(field, typeof(HttpQueryStringAttribute));

                
// If has HttpQueryStringAttribute, this field is for a query string.
                if (attribute != null)
                {
                    SetField(field, attribute);
                }
            }
        }

        
/// <summary>
        
/// Set field according to the HttpQueryStringAttribute.
        
/// </summary>
        
/// <param name="field">The field will be set</param>
        
/// <param name="attribute">The attribute of current field</param>
        private void SetField(FieldInfo field, HttpQueryStringAttribute attribute)
        {
            
// The query string must be provided.
            if (attribute.IsRequired)
            {
                
if (Request.QueryString[attribute.Name] != null)
                {
                    SetFieldValue(field, 
this, attribute.Name, field.FieldType);
                }
                
else
                {
                    
throw new Exception(string.Format("Query string \"{0}\" is required", attribute.Name), new NullReferenceException());
                }
            }
            
// If the query string is not be provided, using the default value.
            else
            {
                
if (attribute.DefaultValue == null || field.FieldType == attribute.DefaultValue.GetType())
                {
                    
if (Request.QueryString[attribute.Name] == null || Request.QueryString[attribute.Name] == string.Empty)
                    {
                        field.SetValue(
this, attribute.DefaultValue);
                    }
                    
else
                    {
                        SetFieldValue(field, 
this, attribute.Name, field.FieldType);
                    }
                }
                
else
                {
                    
throw new Exception(string.Format("Invalid default value of query string \"{0}\"({1})", attribute.Name, field.Name), new NullReferenceException());
                }
            }
        }

        
/// <summary>
        
/// Set the value of current field according to the query string.
        
/// </summary>
        
/// <param name="field">The field will be set</param>
        
/// <param name="obj">The object whose field value will be set</param>
        
/// <param name="name">The name of query string</param>
        
/// <param name="conversionType">The type to be converted</param>
        private void SetFieldValue(FieldInfo field, object obj, string name, Type conversionType)
        {
            
try
            {
                
// Set field value.
                field.SetValue(obj, Convert.ChangeType(Request.QueryString[name], conversionType));
            }
            
catch (Exception ex)
            {
                
throw new Exception(string.Format("The given value of query string \"{0}\" can not be convert to {1}", name, conversionType), ex);
            }
        }
    }
}

在页面里,这样写就OK了(Default.aspx.cs):

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using GooKuu.Framework.Web;

public partial class _Default : PageBase
{
    
    
/// <summary>
    
/// Name 是Query String的名字,"Anonymous"是缺省值。
    
/// 如果没有提供这个Query String,就采用缺省值。
    
/// </summary>
    [HttpQueryString("Name""Anonymous")]
    
public string name;

    
/// <summary>
    
/// UserId 是Query String的名字,不提供缺省值。
    
/// 如果没有提供这个Query String或者提供的格式不正确导致转换失败,都会抛出异常。
    
/// </summary>
    [HttpQueryString("UserId")]
    
public int userId;

    
protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(
string.Format("Name is {0}<br/>", name));
        Response.Write(
string.Format("UserId is {0}<br/>", userId));
    }
}

posted on 2006-01-16 11:01  Ariel Y.  阅读(5987)  评论(28编辑  收藏  举报