asp.net中Request请求参数的自动封装
这两天在测一个小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请求参数的自动封装的更多相关文章
- 详细解析ASP.NET中Request接收参数乱码原理
起因:今天早上被同事问了一个问题:说接收到的参数是乱码,让我帮着解决一下. 实际情景: 同事负责的平台是Ext.js框架搭建的,web.config配置文件里配置了全局为“GB2312”编码: < ...
- Asp.net中Request.Url的各个属性对应的意义介绍
Asp.net中Request.Url的各个属性对应的意义介绍 本文转载自 http://www.jb51.net/article/30254.htm 网络上关于Request.Url的说明已经很多也 ...
- SpringMVC中post请求参数注解@requestBody使用问题
一.httpClient发送Post 原文https://www.cnblogs.com/Vdiao/p/5339487.html public static String httpPostWithJ ...
- 用WIN7系统IIS的提示:数据库连接出错,请检查Conn.asp文件中的数据库参数设置
我用科讯的从4.0开始,去年开始很少用科讯做新站了,今天拿来做一下,结果悲剧了,数据库路径老是不对,百度一番又一番的,,最后终于给度娘解决了.分享出来给遇到同样的问题的人. 用WIN7系统IIS的注意 ...
- ASP.NET中使用JavaScript实现图片自动水平滚动效果
参照网上的资料,在ASP.NET中使用JavaScript实现图片自动水平滚动效果. 1.页面前台代码: <%@ Page Language="C#" AutoEventWi ...
- js处理url中的请求参数(编码/解码)
在处理 a 链接跳转其他页面时,总会遇到需要传递一些当前页面的信息到其他页面,然后其他页面利用这些信息进行相关操作.利用 get 请求或 hash 传递是常见的方式. 首先,需要对传递的参数进行编码, ...
- request请求参数与http请求过程
request请求参数
- angular开发中对请求数据层的封装
代码地址如下:http://www.demodashi.com/demo/11481.html 一.本章节仅仅是对angular4项目开发中数据请求封装到model中 仅仅是在项目angular4项目 ...
- http.request请求及在node中post请求参数解析
Post请求 var http=require('http'); var qs=require('querystring'); var post_data={a:123,time:new Date() ...
随机推荐
- tomcat 下安装 MantisBT
环境 OS:win8.1 up1 64bit tomcat :9.0.0 64bit php: php-7.1.7-nts-Win32-VC14-x64.zip postgres: postgresq ...
- trace-cmd使用方法
使用trace-cmd有的时候没有来得及使用ctrl+c, 导致出现多个trace.dat.cpu*, 可以使用下面的办法来手动合并trace.dat If a crash happened on a ...
- THINKPHP5 volist标签循环不能设置循环变量为$i
在thinkphp5的volist标签中不要用$i作为id,举个简单例子 控制器这样写 模板这样写 结果是 这很令人费解啊.然后换一个循环变量看看 循环正常了,看来这个id这里设置循环变量的时候 不能 ...
- php的opcache缓存扩展
opcache (全程 zend opcache): 从php5.5开始,默认提供的php脚本缓存扩展,编译php5.5时加上参数--enable-opcache就可以编译opcache了,只是要启用 ...
- Linux Platform驱动模型(三) _platform+cdev
平台总线是一种实现设备信息与驱动方法相分离的方法,利用这种方法,我们可以写出一个更像样一点的字符设备驱动,即使用cdev作为接口,平台总线作为分离方式: xjkeydrv_init():模块加载函数 ...
- scala 模式匹配详解 3 模式匹配的核心功能是解构
http://www.artima.com/scalazine/articles/pattern_matching.html这篇文章是odersky谈scala中的模式匹配的一段对话,我做了部分片段翻 ...
- 机器人学 —— 轨迹规划(Artificial Potential)
今天终于完成了机器人轨迹规划的最后一次课了,拜拜自带B - BOX 的 Prof. TJ Taylor. 最后一节课的内容是利用势场来进行轨迹规划.此方法的思路非常清晰,针对Configration ...
- SSL、数字签名、CA 工作原理通俗描述
SSL(Secure Socket Layer) 是一种加密技术,可以提供对称加密和非对称加密.由于它在协议层里正好是在传输层与应用层之间,这就决定了上层应用必须经过它,这就是它广泛流行和易于实现的原 ...
- rayleighchan实现瑞利多径衰落信
rayleighchan实现瑞利多径衰落信道 1.命令格式: chan = rayleighchan(ts,fd,tau,pdb) 其中: ts—为输入信号的采样周期, fd—就是Doppler频偏, ...
- Python 读、写、追加csv文件详细以及注意事项
一.利用csv库创建文件 首先导入csv文件 import csv 根据指定的path创建文件: def create_csv(path): with open(path, "w+" ...