这两天在测一个小Demo的时候发现一个很蛋疼的问题----请求参数的获取和封装,例:

  方便测试用所以这里是一个很简单的表单.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form action="RequestHandler.ashx">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="Username" /></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="text" name="UserPwd" /></td>
            </tr>
            <tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
        </table>
    </form>
</body>
</html>

    有一个和表单对应的实体类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class EUser
{
    public string Username { get; set; }
    public string UserPwd { get; set; }
}

  在RequestHandler中我们这样做:

<%@ WebHandler Language="C#" Class="RequestHandler" %>

using System;
using System.Web;

public class RequestHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        EUser user = new EUser
        {//下面的操作相信不少像我一样的同学已经做的要吐了..
            Username = context.Request["Username"],
            UserPwd = context.Request["UserPwd"]
        };
        //之后对User进行业务处理....
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

  因为这里测试用所以只有两个字段,假如这里有10个20个字段,是不是有懵逼的感觉,时间长了有木有感觉这样写代码真的很low.一不小心键名复制错了还会出错.自从大二开始学asp一直到现在这操作也不知道多少回了...

  对于用惯了Struts2和asp.net mvc自动封装功能的同学来说还写这个,是不是有一种开了飞机回来一趟却要踩滑板车一步一步蹬的感觉..

  前两天做一个java小项目的时候用到了一个很好用的工具beanutils,它可以帮我们很轻易的封装请求参数,受到它的启发我写了一个小工具类,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Reflection;
using System.Collections.Specialized;

namespace zze
{
    public class NotANumber : Exception
    {
        public NotANumber(string message)
            : base(message) { }
    }
    public class DateFormatError : Exception
    {
        public DateFormatError(string message)
            : base(message) { }
    }
    public class BeanUtil
    {
        public static T FillBean<T>(HttpRequest request)
        {
            PropertyInfo[] Properties = typeof(T).GetProperties();
            T bean = Activator.CreateInstance<T>();
            NameValueCollection nameVals = request.Form;
            ; i < nameVals.Count; i++)
            {
                string keyStr = nameVals.GetKey(i);
                StringBuilder valStr = new StringBuilder();
                string[] vals = nameVals.GetValues(i);
                )
                {
                    ; j < vals.Length; j++)
                    {
                        )
                        {
                            valStr.Append(vals[j] + ",");
                        }
                        else
                        {
                            valStr.Append(vals[j]);
                        }
                    }
                }
                else
                {
                    valStr.Append(vals[]);
                }
                foreach (PropertyInfo pro in Properties)//遍历该类所有属性
                {
                    if (pro.Name.ToLower().Equals(keyStr.ToLower()))
                    {
                        pro.SetValue(bean, valStr.ToString());
                    }
                }
            }
            return bean;
        }

        public static void CopyProperties<T,W>(T source, W target)
        {
            PropertyInfo[] Properties = typeof(T).GetProperties();
            PropertyInfo[] wProperties = typeof(W).GetProperties();
            foreach (PropertyInfo wPro in wProperties)//遍历该类所有属性
            {
                foreach (PropertyInfo pro in Properties)//遍历该类所有属性
                {
                    if (wPro.Name.ToLower().Equals(pro.Name.ToLower()) && wPro.PropertyType.Equals(pro.PropertyType))
                    {
                        wPro.SetValue(target, pro.GetValue(source));
                    }
                    else if (wPro.Name.ToLower().Equals(pro.Name.ToLower()) && !wPro.PropertyType.Equals(pro.PropertyType))
                    {
                        if (wPro.PropertyType.Equals(typeof(DateTime)))
                        {
                            try
                            {
                                wPro.SetValue(target, Convert.ToDateTime(pro.GetValue(source)));
                            }
                            catch (Exception)
                            {
                                throw new DateFormatError("日期格式不正确");
                            }

                            break;
                        }
                        if (wPro.PropertyType.Equals(typeof(int)))
                        {
                            try
                            {
                                wPro.SetValue(target, Convert.ToInt32(pro.GetValue(source)));
                            }
                            catch (Exception)
                            {
                                throw new NotANumber("输入的不是一个数字");
                            }
                            break;
                        }
                        if (wPro.PropertyType.Equals(typeof(double)) || wPro.PropertyType.Equals(typeof(float)))
                        {
                            try
                            {
                                wPro.SetValue(target, Convert.ToDouble(pro.GetValue(source)));
                            }
                            catch (Exception)
                            {
                                throw new NotANumber("输入的不是一个数字");
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

}

  接下来刚才我们的封装就可以改成这样:

<%@ WebHandler Language="C#" Class="RequestHandler" %>

using System;
using System.Web;
using zze;
public class RequestHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        EUser user = BeanUtil.FillBean<EUser>(context.Request);
        //之后对User进行业务处理....
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

  是不是简短清新了很多,注意这里的EUser属性名要和Request中的参数键名相同.

  此时有些同学可能注意到了,我们之前的属性都是string类型的,所以表单中的数据可以很容易的通过反射进行赋值,假如我们属性中出现了其它类型呢?如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form action="RequestHandler.ashx">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username" /></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="text" name="userPwd" /></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="text" name="Age" /></td>
            </tr>
            <tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
        </table>

    </form>
</body>
</html>

    此时我们有个年龄字段,作为demo演示我们可以给它int类型.

    这里按照beanutils的使用来说,因为用户在前台页面上的输入都可以用字符串来接收,所以我们可以用一个和页面表单对应的而且属性类型都是string实体来接收,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class UserFormBean
{
    public string Username { get; set; }
    public string UserPwd { get; set; }
    public string Age { get; set; }
}

  这个实体没什么业务意义,纯粹用来接收来自请求的参数内容,与其对应的实体如下,包含一个int属性:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class EUser
{
    public string Username { get; set; }
    public string UserPwd { get; set; }
    public int Age { get; set; }
}

  RequestHandler就可以改成如下代码了:

<%@ WebHandler Language="C#" Class="RequestHandler" %>

using System;
using System.Web;
using zze;
public class RequestHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        UserFormBean userFormBean = BeanUtil.FillBean<UserFormBean>(context.Request);
        EUser user = new EUser();
        BeanUtil.CopyProperties<UserFormBean, EUser>(userFormBean, user);//该方法的作用是将一个属性和其对应的对象的值copy给自己,并完成相应属性的类型转换,第一个参数是copy的来源,第二个参数是copy的目标
        //之后对User进行业务处理....
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

  执行上述代码会发现EUser中的age会成功赋值,当然前台age文本框的值要符合int格式.  

asp.net中Request请求参数的自动封装的更多相关文章

  1. 详细解析ASP.NET中Request接收参数乱码原理

    起因:今天早上被同事问了一个问题:说接收到的参数是乱码,让我帮着解决一下. 实际情景: 同事负责的平台是Ext.js框架搭建的,web.config配置文件里配置了全局为“GB2312”编码: < ...

  2. Asp.net中Request.Url的各个属性对应的意义介绍

    Asp.net中Request.Url的各个属性对应的意义介绍 本文转载自 http://www.jb51.net/article/30254.htm 网络上关于Request.Url的说明已经很多也 ...

  3. SpringMVC中post请求参数注解@requestBody使用问题

    一.httpClient发送Post 原文https://www.cnblogs.com/Vdiao/p/5339487.html public static String httpPostWithJ ...

  4. 用WIN7系统IIS的提示:数据库连接出错,请检查Conn.asp文件中的数据库参数设置

    我用科讯的从4.0开始,去年开始很少用科讯做新站了,今天拿来做一下,结果悲剧了,数据库路径老是不对,百度一番又一番的,,最后终于给度娘解决了.分享出来给遇到同样的问题的人. 用WIN7系统IIS的注意 ...

  5. ASP.NET中使用JavaScript实现图片自动水平滚动效果

    参照网上的资料,在ASP.NET中使用JavaScript实现图片自动水平滚动效果. 1.页面前台代码: <%@ Page Language="C#" AutoEventWi ...

  6. js处理url中的请求参数(编码/解码)

    在处理 a 链接跳转其他页面时,总会遇到需要传递一些当前页面的信息到其他页面,然后其他页面利用这些信息进行相关操作.利用 get 请求或 hash 传递是常见的方式. 首先,需要对传递的参数进行编码, ...

  7. request请求参数与http请求过程

    request请求参数

  8. angular开发中对请求数据层的封装

    代码地址如下:http://www.demodashi.com/demo/11481.html 一.本章节仅仅是对angular4项目开发中数据请求封装到model中 仅仅是在项目angular4项目 ...

  9. http.request请求及在node中post请求参数解析

    Post请求 var http=require('http'); var qs=require('querystring'); var post_data={a:123,time:new Date() ...

随机推荐

  1. mysql连接时提示错误太多的解决

    mysqladmin flush-hosts -uroot -p -h127.0.0.1 -P3306 然后输入密码就可以了

  2. python分支语句

    一.if else语句 if 条件表达式: else: a = 3 b = 4 if a >= b: print("a >= b") else: print(" ...

  3. nginx 动静分离(相同URL)

    #报表 location ~* /(report)/ { if ($request_uri !~* .*(jd|taobao|operator).* ){ proxy_pass http://tweb ...

  4. rsync 常用参数

    rsync 常用参数的具体解释如下: -v, --verbose 详细模式输出-q, --quiet 精简输出模式-c, --checksum 打开校验开关,强制对文件传输进行校验-a, --arch ...

  5. hdparm命令(转)

    转自:http://man.linuxde.net/hdparm hdparm命令提供了一个命令行的接口用于读取和设置IDE或SCSI硬盘参数. 语法 hdparm(选项)(参数) 选项 -a< ...

  6. shell脚本之流程控制语句

    一.分支控制语句 1.if .. fi条件 if condition; then action fi 2.if .. else .. fi条件 if condition;then action; el ...

  7. iOS ARC编译器规则和内存管理规则

    iOS 开发当中,自动引用计数已经是标准的内存管理方案.除了一些老旧的项目或者库已经没有人使用手动来管理内存了吧. ARC无疑是把开发者从繁琐的保留/释放引用对象逻辑中解脱出来.但这并不是万事大吉了, ...

  8. 关于数据库DML、DDL、DCL区别

    总体解释:DML(data manipulation language):       它们是SELECT.UPDATE.INSERT.DELETE,就象它的名字一样,这4条命令是用来对数据库里的数据 ...

  9. 搭建Kubernetes服务集群遇到的问题

    kube-proxy问题: Apr 12 09:42:49 compute1 kube-proxy[12965]: E0412 09:42:49.602342 12965 reflector.go:2 ...

  10. LeetCode 748 Shortest Completing Word 解题报告

    题目要求 Find the minimum length word from a given dictionary words, which has all the letters from the ...