这两天在测一个小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. Spark搭建HA具体解释

    实验环境: zookeeper-3.4.6 Spark:1.6.0 简单介绍: 本篇博客将从下面几点组织文章: 一:Spark 构建高可用HA架构 二:动手实战构建高可用HA 三:提交程序測试HA 一 ...

  2. DES ECB 模式 JAVA PHP C# 实现 加密 解密 兼容

    版本一: JAVA: import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.BASE64Decoder; i ...

  3. java调用删除文件的方法删除文件,却删除不干净

    场景: 程序中在做数据下载时,生成了一个临时文件夹.夹子里面有一些txt和其他格式文件. 数据下载完毕后,需要删除这个临时文件夹,但是一直删除不干净,总会有一下文件残留. 网搜到了这个问题的原因: 内 ...

  4. python使用requests发送multipart/form-data请求数据

    def client_post_mutipart_formdata_requests(request_url,requestdict): #功能说明:发送以多部分表单数据格式(它要求post的消息体分 ...

  5. POST 发送HTTP请求入参为:String url, Map<String, Object> propsMap

    /** * 发送HTTP请求 * * @param url * @param propsMap * 发送的参数 */ public static String httpSend(String url, ...

  6. js中的XMLHTTPRequest

    window.onload = function(){ //var url = "http://localhost:8000/sales.json"; var url = &quo ...

  7. 删除新版UniAccess Agent 办公室监控软件的方法

    UniAccess Agent 是在由LeagSoft开发的监控软件,老版本的一般安装在C:\Program Files\LeagSoft\UniAccess Agent这个目录下,一般找到这个目录点 ...

  8. openresty的安装和使用

    1,简介 OpenResty(又称:ngx_openresty) 是一个基于 NGINX 的可伸缩的 Web 平台,是一个强大的 Web 应用服务器,在性能方面,OpenResty可以 快速构造出足以 ...

  9. 爬虫----爬虫请求库requests

    一 介绍 介绍:---------------------------------------------使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的a ...

  10. bootstrap 弹出框实现点击后打开离开后关闭

    $("#PersonName").popover({ trigger: 'manual', placement: 'bottom', //title: '<div style ...