C# 中没有四舍五入函数,程序语言都没有四舍五入函数,因为四舍五入算法不科学,国际通行的是 Banker 舍入法Bankers rounding(银行家舍入)算法,即四舍六入五取偶。事实上这也是 IEEE 规定的舍入标准。因此所有符合 IEEE 标准的语言都应该是采用这一算法的Math.Round 方法默认的也是 Banker 舍入法在 .NET 2.0 中 Math.Round 方法有几个重载方法Math.Round(Decimal, MidpointRounding)Math.Round(Double, MidpointRounding)Math.Round(Decimal, Int32, MidpointRounding)Math.Round(Double, Int32, MidpointRounding)将小数值舍入到指定精度。MidpointRounding 参数,指定当一个值正好处于另两个数中间时如何舍入那个值该参数是个 MidpointRounding 枚举此枚举有两个成员,MSDN 中的说明是:AwayFromZero 当一个数字是其他两个数字的中间值时,会将其舍入为两个值中绝对值较小的值。ToEven 当一个数字是其他两个数字的中间值时,会将其舍入为最接近的偶数。注 意!这里关于 MidpointRounding.AwayFromZero 的说明是过错的!实际舍入为两个值中绝对值较大的值。不过 MSDN 中的 例子是正确的,英文描述原文是 it is rounded toward the nearest number that is away from zero.所以,要实现四舍五入函数,对于正数,可以加一个 MidpointRounding.AwayFromZero 参数指定当一个数字是其他两个数字的中间值时其舍入为两个值中绝对值较大的值,例:Math.Round(3.45, 2, MidpointRounding.AwayFromZero)不过对于负数上面的方法就又不对了因此需要自己写个函数来处理第一个函数:double Round(double value, int decimals){if (value < 0){return Math.Round(value + 5 / Math.Pow(10, decimals + 1), decimals, MidpointRounding.AwayFromZero);}else{return Math.Round(value, decimals, MidpointRounding.AwayFromZero);}} 第二个函数:double Round(double d, int i){if(d >=0){d += 5 * Math.Pow(10, -(i + 1));}else{d += -5 * Math.Pow(10, […]
View Details<% if request("infoid")<>"" then set rs=conn.execute("select * from nproduct where id="&request("infoid")) if not (rs.eof and rs.bof) then proname=rs("proname") content=rs("proinfo") end if rs.close set rs=nothing end if %> 早几天在系统中添加文件管理的下载功能, 要求在ASPX文件中实现, 以进行权限的控件,于是添加下列代码: … Response.ContentType = mime; //相应的MIME TYPE Response.AppendHeader("Content-Disposition", "attachment; filename=\"" +fileName + "\""); Response.BinaryWrite(bytes); Response.End(); … 当fileName中包含中文时, 文件下载保存时, 文件名变成了乱码, 需要用户修改,这也就违被了我设定预设文件名的初衷. 解决办法1: 对fileName进行URL编码, 把下划线标注的那句改为Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + Server.UrlEncode(fileName) + "\"");便可. 虽然中文乱码问题解决了, 但是还有一个问题: 在测试时, 下载保存的文件名有时会变成该页面的名字(.aspx), 虽然可以把内容下载到本地, 但是需要更改文件名及类型, 这样会给用户带来很大的困惑. 还有一个办法, 可以很简单的解决以上的两个问题: 解决办法2: 假设当前的URL为 http://localhost/download.aspx?id=123, fileName为"下载.pdf", 我们只要把下载URL改为 http://localhost/download.aspx/下载.pdf?id=123 可, 上面下划线标注的那句代码则可以注释掉了, 试一下, 结果一定让你非常满意! 转自:http://www.webshu.net/jiaocheng/programme/ASPNET/200606/1427.html
View Details昨天在用IIS部署一个WCF服务时,碰到了如下错误: 理解了文档内容,但无法进行处理。 – WSDL 文档包含无法解析的链接。 – 下载“http://admin-pc/IISHostService/Service1.svc?xsd=xsd0”时出错。 – 基础连接已经关闭: 接收时发生错误。 – 无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接。。 – 远程主机强迫关闭了一个现有的连接。 元数据包含无法解析的引用:“http://admin-pc/IISHostService/Service1.svc?wsdl”。 元数据包含无法解析的引用:“http://admin-pc/IISHostService/Service1.svc?wsdl”。 如果该服务已在当前解决方案中定义,请尝试生成该解决方案,然后再次添加服务引用。 该错误是在使用svcutil生成client代码时报的错误,服务是部署在IIS7上,部署的过程都是完全教科书式的进行。服务也正常启动了,显示如下内容 已创建服务。 若要测试此服务,需要创建一个客户端,并将其用于调用该服务。可以使用下列语法,从命令行中使用 svcutil.exe 工具来进行此操作:
1 |
<strong>svcutil.exe </strong><a href="http://leo-pc/IISHostService/Service1.svc?wsdl"><strong>http://leo-pc/IISHostService/Service1.svc?wsdl</strong></a> |
按照提示直接用svcutil.exe http://admin-pc/IISHostService/Service1.svc?wsdl命令去生成代码,就出现了开头说的那个错误。而如果用visual studio的webdevserver启动,则一切正常。 经过一轮谷百之后,发现网上有很多类似的情况,有的说是因为用了wsHttpBinding协议引起的,或者是元数据没有正确公开,但都不是他们说的情况。后来找到了一篇文章,说的是添加WCF引用的一个陷阱。里面提到的情形跟我遇到的一致,原来问题出在权限,难怪用webdevserver可以很正常的运行。原来在下载http://admin-pc/IISHostService/Service1.svc?xsd=xsd0时的权限不足,在浏览器直接访问这个url会提示找不到页面。原因就是IIS进程的用户没有访问Windows\Temp目录的权限。找到Temp目录,然后找到IIS_USER用户,授权即可。 具体可参考:http://merill.net/2008/04/wcf-add-service-reference-gotcha-with-windows-server/ 转自:http://www.cnblogs.com/shenba/archive/2012/01/06/2313932.html
View Details在Asp.Net中对页面分页的方法很多,可以直接用sql语句分,也可以使用.net提供的PageDataSource类来分页,显示的视图同样可以使用第三方控件AspNetPager等来显示,下面就来重点说说这几种分页方式: 一般情况下我们都是通过sql语句来分页,这在无论哪种开发语音都是通用的, 使用sql语句或者存储过程分页的方式最主要的是要在读取数据的时候把sql语句或者存储过程写好,它的原理是只读取当前要显示的几行记录,所以要根据页数和每页显示的数目来写语句,如下: 很显然只要将pageSize和Page作为参数就可以了,然后再前台调用的时候只要指定当前页数和每页显示的数目,就可以实现分页了,为了显示总数目,还可以读取所有数目,可以通过url来传递页码,如果总记录数位count,每页显示的数目为pageSize,那么总页数就是pageCount=((count-1)/pageSize)+1,在读取的时候代码如下: int rowLine = (currentPage – 1) *pageSize; sql = "Select top pageSize * from News where id not in(select top rowLine id from News)" 然后在页面中 int pp=1; DataSet ds = TransactionsBLL.GetList(kid, pp); DataSet ds1 = TransactionsBLL.GetList(kid); int count = ds1.Tables[0].Rows.Count; int pageCount = ((count-8-1) /16) + 1; if (pp < pageCount) { lblFy.Text = "共" + count + "条 <a href='?id=" + cid + "&pager=1′>首页</a> <a href='?id=" + cid + "&pager=" + (pp – 1) + "'>上一页</a> <a href='?id=" + cid + "&pager=" + (pp + 1) + "'>下一页</a> <a href='?id=" + cid + "&pager=" + pageCount + "'>尾页</a> 当前第" + pp + "页/共" + pageCount + "页"; } else { lblFy.Text = "共" + count + "条 <a href='?id=" + cid + "&pager=1′>首页</a> <a href='?id=" + cid + "&pager=" + (pp – 1) + "'>上一页</a> <a href='?id=" + cid + "&pager=" + pageCount + "'>下一页</a> <a href='?id=" + cid + "&pager=" + pageCount + "'>尾页</a> 当前第" + pp + "页/共" + pageCount + "页"; } 随便粘贴的代码,大概就是这样子的 需要注意的时候,由于.net在回传的时候不保存当前页,所以如果使用按钮进行分页的时候需要使用ViewState来保存页数,每次只读取所需要的几条记录,所以适合做大型网站数量比较大的时候使用,一般的分页都比较简单,如果有这种情况,比如说有10条数据,要求第一页显示2条,其他的页数都显示4条,那么就我们知道就显示3页就可以了,这个要怎么实现呢,其实这个只需要我们稍微判断下就可以了 代码: View Code public DataSet GetList(int pp) { string sql = null; DataSet ds = null; if (pp == 1 || pp == 0) { //第一页的时候显示2行数据 sql = "Select top 2 * from News" } else { //第二页的时候显示除了第一页的2条数据之外的前4条数据 if (pp == 2) { sql = "Select top 4 * from News where id not in(select top 2 id from News)"; } else { //第三页和之后的页显示 (pp – 2) *4 然后在加上第一页的2条,也就是(pp – 2) *4+2条数据之外的前4条数据 int rowLine = (pp – 2) *4+2; sql = "Select top pageSize * from News where id not in(select top rowLine id from News)" } } ds = SqlHelper.ExecuteDataSet(CommandType.Text, sql); return ds; } 然后在页面里我们要获得页数 int pageCount = (((count-2-1) /4) + 1)+1; 一般的情况下pageCount=((count-1) /4) + 1 在这里我们可以先去掉第一页显示的2条数据,然后进行分页,假如是2页,那么因为还有第一页,所以这里还需要在后面再加上一页,也就是 (((count-2-1) /4) + 1)+1; 另外一种分页方式就是使用.net提供的PageDataSource类来分页, PageDataSource是微软提供一个用于分页使用的类,集成了绑定控件的一些方法,在使用的时候,我们只需要从数据库读取我们所要的数据,绑定到PageDataSource即可,然后允许PageDataSource可以分页,指定当前页和每页要显示的数目,这样就可以很好的获得的总的数目,结合控件,ViewState就可以完成自定义分页视图,方法如下: PagedDataSource pageDataSource = new PagedDataSource(); pageDataSource.DataSource = NewsManager.GetNews();//所有记录 pageDataSource.AllowPaging = true; pageDataSource.PageSize […]
View Details处理图片时常用的过程是:读入图片文件并转化为Bitmap -> 处理此Bitmap的每个点以得到需要的效果 -> 保存新的Bitmap到文件 使用C#很方便的就可以把多种格式的图片文件读到Bitmap对象中。一句话就够了,常见的格式都支持,诸如JPEG,BMP,PNG等等。 Bitmap bmp = new Bitmap("文件名"); 然后就是怎么处理这个图片的问题了,与本案无关,pass。 最后就是保存。JPEG虽然是有损压缩方案,但是它在缩减文件体积和尽可能好的保留原有信息的矛盾上很好的找到了平衡点,所以在很多情况下成为首选的保存方案。 C#当然不会无视这一点,Bitmap类提供了默认的另存为JPEG的方法: bmp.Save("输出文件", System.Drawing.Imaging.ImageFormat.Jpeg); 这样当然很方便,但有时候更在乎文件体积而有时候更在乎图像质量,是不是有什么办法可以让自己来控制压缩质量呢? 答案是肯定的,bmp.Save方法中有个重载用到了EncoderParameters参数。我们可以在这个参数中加入自己的控制质量。 /**//// <summary> /// 保存JPG时用 /// </summary> /// <param name="mimeType"></param> /// <returns>得到指定mimeType的ImageCodecInfo</returns> private static ImageCodecInfo GetCodecInfo(string mimeType) { ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo ici in CodecInfo) { if (ici.MimeType == mimeType) return ici; } return null; } /**//// <summary> /// 保存为JPEG格式,支持压缩质量选项 /// </summary> /// <param name="bmp"></param> /// <param name="FileName"></param> /// <param name="Qty"></param> /// <returns></returns> public static bool KiSaveAsJPEG(Bitmap bmp, string FileName, int Qty) { try { EncoderParameter p; EncoderParameters ps; […]
View DetailsQR二维码比其他二维码相比,具有识读速度快、数据密度大、占用空间小的优势。QR码的三个角上有三个寻象图形,使用CCD识读设备来探测码的位置、大小、倾斜角度、并加以解码,实现360度高速识读。每秒可以识读30个含有100个字符QR码。QR码容量密度 大,可以放入1817个汉字、7089个数字、4200个英文字母。QR码用数据压缩方式表示汉字,仅用13bit即可表示一个汉字,比其他二维条码表示汉字的效率提高了20%。QR具有4个等级的纠错功能,即使破损也能够正确识读。QR码抗弯曲的性能强,通过QR码中的每隔一定的间隔配置有校正图形,从码的外形来求得推测校正图形中心点与实际校正图形中心点的误差来修正各个模快的中心距离,即使将QR码贴在弯曲的物品上也能够快速识读。QR码可以分割成16个QR码,可以一次性识读数个分割码,适应于印刷面积有限及细长空间印刷的需要。此外微型QR码可以在1厘米的空间内放入35个数字或9个汉字或21个英文字母,适合对小型电路板对ID号码进行采集的需要。(From:http://tuqiang9999.blog.163.com/blog/static/33241320111115103159542/) QRCode下载地址:ThoughtWorks.QRCode(支持中文) 一、项目引用QRCode的DLL文件(ThoughtWorks.QRCode.dll) 二、ASPX页面(两个jquery的js文件请自行去官网下载): <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>二维码工具测试</title> <script type="text/javascript" src="../../Scripts/Jquery/jquery-1.6.2.js"></script> <script type="text/javascript" src="../../Scripts/Jquery/jquery.form.js"></script> <script type="text/javascript" src="js/test.js"></script> <style type="text/css"> .style1 { width: 100%; } #txt_qr { width: 632px; } </style> </head> <body> <div> <table class="style1"> <tr> <td> 输入文字: </td> <td> <input type="text" id="txt_qr" name="txt_qr" /> </td> </tr> <tr> <td> 二维码图片 </td> <td> <img id="qrimg" alt="二维码图片" /> </td> </tr> <tr> <td> 生成选项 </td> <td> Encoding:<select id="Encoding"> <option value="Byte">Byte</option> <option value="AlphaNumeric">AlphaNumeric</option> <option value="Numeric">Numeric</option> </select> Correction Level:<select id="Level"> <option value="M">M</option> <option value="L">L</option> <option value="Q">Q</option> <option value="H">H</option> </select> Version:<input id="txt_ver" type="text" value="7" />(1-40) Size:<input id="txt_size" type="text" value="4" /> </td> </tr> <tr> <td colspan="4"> <input type="button" onclick="getQrImg();" value="生成二维码" /> </td> </tr> <tr> <td> <form id="qrForm" action="Ashx/test.ashx" method="post" enctype="multipart/form-data"> <input type="file" id="file_qr" name="file_qr" /><input type="submit" value="读取二维码" /> </form> </td> <td colspan="1"> <img id="img_qr" alt="要读取的图片" /><br /> <input id="txt_readqr" type="text" /> </td> </tr> </table> </div> </body> </html> 三、test.js文件 [javascript] $(document).ready(function () { var options = { beforeSubmit: showRequest, […]
View Details一、Views文件夹 -> Shared文件夹下的 _Layout.cshtml 母版页 @RenderBody 当创建基于_Layout.cshtml布局页面的视图时,视图的内容会和布局页面合并,而新创建视图的内容会通过_Layout.cshtml布局页面的@RenderBody()方法呈现在标签之间。 @RenderPage 从名称可以猜出来这个方法是要呈现一个页面。比如网页中固定的头部可以单独放在一个共享的视图文件中,然后在布局页面中通过这个方法调用,用法如下: @RenderPage(“~/Views/Shared/_Header.cshtml”) 带参数 @RenderPage(“~/Views/Shared/_Header.cshtml”,new{parm="my",parm2="you") 调用页面获取参数: //获取 RenderPage() 传递过来的参数 @PageData["param"] @RenderSection 布局页面还有节(Section)的概念,也就是说,如果某个视图模板中定义了一个节,那么可以把它单独呈现出来 为了防止因缺少节而出现异常,可以给RenderSection()提供第2个参数: @RenderSection("head", false) 或 @if (IsSectionDefined("head")) { @RenderSection("head", false) } else { <p>SubMenu Section is not defined!</p> } 代码如下: [html] view plaincopy <!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> @RenderSection("head", required: true)@*View页面自定义特定js/css使用*@ </head> <body> @RenderPage("~/Views/Shared/_Header.cshtml") @RenderBody() </body> </html> 二、创建视图,使用母版页 代码如下: [html] view plaincopy @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> @section Head{ <script type="text/javascript"> $(function () { alert("hello jquery"); }); </script> } <p>执行C#普通语法</p><br /> @DateTime.Now.Date.ToShortDateString() <p>执行C#语句段</p> @{ List<string> list = new List<string> { "Mvc3", "Razor" }; list.Add(".Net4"); } <ul> @foreach(string s in list) { if (string.IsNullOrEmpty(s)) { <li>空</li> } else […]
View Details设当前页完整地址是:http://www.jb51.net/aaa/bbb.aspx?id=5&name=kelli "http://"是协议名 "www.jb51.net"是域名 "aaa"是站点名 "bbb.aspx"是页面名(文件名) "id=5&name=kelli"是参数 【1】获取 完整url (协议名+域名+站点名+文件名+参数) 复制代码代码如下: string url=Request.Url.ToString(); url= http://www.jb51.net/aaa/bbb.aspx?id=5&name=kelli 【2】获取 站点名+页面名+参数: 复制代码代码如下: string url=Request.RawUrl; (或 string url=Request.Url.PathAndQuery;) url= /aaa/bbb.aspx?id=5&name=kelli 【3】获取 站点名+页面名: 复制代码代码如下: string url=HttpContext.Current.Request.Url.AbsolutePath; (或 string url= HttpContext.Current.Request.Path;) url= aaa/bbb.aspx 【4】获取 域名: 复制代码代码如下: string url=HttpContext.Current.Request.Url.Host; url= www.jb51.net 【5】获取 参数: 复制代码代码如下: string url= HttpContext.Current.Request.Url.Query; url= ?id=5&name=kelli 复制代码代码如下: Request.RawUrl:获取客户端请求的URL信息(不包括主机和端口)——>/Default2.aspx Request.ApplicationPath:获取服务器上ASP.NET应用程序的虚拟路径。——>/ Request.CurrentExecutionFilePath:获取当前请求的虚拟路径。——>/Default2.aspx Request.Path:获取当前请求的虚拟路径。——>/Default2.aspx Request.PathInfo:取具有URL扩展名的资源的附加路径信息——> Request.PhysicalPath:获取与请求的URL相对应的物理文件系统路径。——>E:\temp\Default2.aspx Request.Url.LocalPath:——>/Default2.aspx Request.Url.AbsoluteUri:——>http://localhost:8080/Default2.aspx Request.Url.AbsolutePath:—————————->/Default2.aspx 转自:脚本无忧
View Details1、Byte[] ===== 1. BitConverter 将基础数据类型与字节数组相互转换。注意string不是基础类型,而且该方法在不同平台间传递可能有误。 int i = 13; byte[] bs = BitConverter.GetBytes(i); Console.WriteLine(BitConverter.ToInt32(bs, 0)); 2. Encoding 注意慎用Encoding.Default,其值取自操作系统当前的设置,因此在不同语言版本的操作系统是不相同的。建议使用UTF8或者GetEncoding(”gb2312″)。 string s = "abc"; byte[] bs = Encoding.UTF8.GetBytes(s); Console.WriteLine(Encoding.UTF8.GetString(bs)); 3. BinaryFormatter 以二进制格式将对象或整个连接对象图形序列化和反序列化。 using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; [Serializable] class Data { private int x = 13; public void Test() { Console.WriteLine(x); } } static void Main(string[] args) { Data data = new Data(); MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, data); byte[] bs = stream.ToArray(); MemoryStream stream2 = new MemoryStream(bs); Data data2 = (Data)formatter.Deserialize(stream2); data2.Test(); } […]
View DetailsWeb.Config
1 |
<globalization responseEncoding="gb2312"/> |
CS文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.Text; using System.IO; using System.Xml; using System.Collections; using System.Diagnostics; namespace WebPortal { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { CoreProxy.Class1 c = new CoreProxy.Class1(); c.test1(); } protected void Button2_Click(object sender, EventArgs e) { webquerst1(); } public void webquers2() { string html = null; string url = "http://china.alibaba.com/keyword/promotion.htm?catId=14"; WebRequest req = WebRequest.Create(url); req.Method = "POST"; WebResponse res = req.GetResponse(); Stream receiveStream = res.GetResponseStream(); Encoding encode = Encoding.GetEncoding("gb2312"); StreamReader sr = new StreamReader(receiveStream, encode); char[] readbuffer = new char[256]; int n = sr.Read(readbuffer, 0, 256); while (n > 0) { string str = new string(readbuffer, 0, n); html += str; n = sr.Read(readbuffer, 0, 256); } System.Console.Write(html); } //成功!,利用WebRequest 一次Post提交XML内容 public void webquerst1() { WebRequest request = WebRequest.Create("http://192.168.1.244/WebPortal/PortalHandler.ashx"); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. System.Xml.XmlDocument xmlpostdata = new System.Xml.XmlDocument(); xmlpostdata.Load(Server.MapPath("XML/20097.xml")); string postData = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); //普通字符串内容 //string postData = "你好,1232355 abdcde"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. WebResponse response = request.GetResponse(); // Display the status. //Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. //Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); } protected void Button3_Click(object sender, EventArgs e) { WebClientPost(); } //重点!! 成功 利用Webclient Post 按字段的方式提交每个字段的内容给服务器端 public void WebClientPost() { System.Xml.XmlDocument xmlpostdata = new System.Xml.XmlDocument(); xmlpostdata.Load(Server.MapPath("XML/OrderClient.xml")); string OrderClient = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/Order.xml")); string Order = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/TargetOut.xml")); string TargetOut = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/ArrayOfOrderDetail.xml")); string ArrayOfOrderDetail = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); System.Net.WebClient WebClientObj = new System.Net.WebClient(); System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection(); //添加值域 PostVars.Add("OrderClient", OrderClient); PostVars.Add("Order", Order); PostVars.Add("TargetOut", TargetOut); PostVars.Add("ArrayOfOrderDetail", ArrayOfOrderDetail); try { byte[] byRemoteInfo = WebClientObj.UploadValues("http://192.168.1.244/WebPortal/PlaceOrder.ashx", "POST", PostVars); //下面都没用啦,就上面一句话就可以了 string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo); //这是获取返回信息 Debug.WriteLine(sRemoteInfo); } catch { } } //未测试,使用WebClient 一次性提交POst public static string SendPostRequest(string url, string postString) { byte[] postData = Encoding.UTF8.GetBytes(postString); WebClient client = new WebClient(); client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); client.Headers.Add("ContentLength", postData.Length.ToString()); byte[] responseData = client.UploadData(url, "POST", postData); return Encoding.Default.GetString(responseData); } /// <summary> /// 这个是用WEbRequest 提交到WEbService 的例子 /// </summary> /// <param name="URL"></param> /// <param name="MethodName"></param> /// <param name="Pars"></param> /// <returns></returns> public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; SetWebRequest(request); byte[] data = EncodePars(Pars); WriteRequestData(request, data); return ReadXmlResponse(request.GetResponse()); } private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } private static String ParsToString(Hashtable Pars) { StringBuilder sb = new StringBuilder(); foreach (string k in Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString())); } return sb.ToString(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } protected void Button4_Click(object sender, EventArgs e) { } } } |
ashx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Diagnostics; using System.IO; using System.Xml; namespace WebPortal { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class PortalHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string testGet = context.Request["testGet"]; string testPost = context.Request["testPost"]; Debug.WriteLine(testGet); Debug.WriteLine(testPost); //一次性提交的方式 //获得内容长度 int len = context.Request.ContentLength; //获得所有内容流 StreamReader reader = new StreamReader(context.Request.InputStream); //读取内容 string responseFromServer = reader.ReadToEnd(); //字段提交Post方式 string a1 = context.Request["A1"]; string a2 = context.Request["A2"]; string a3 = context.Request["A3"]; //解析Html编码 string re = HttpUtility.HtmlDecode(a1); XmlDocument xd = new XmlDocument(); //加载XML xd.LoadXml(re); context.Response.ContentType = "text/plain"; context.Response.Write(testGet); } public bool IsReusable { get { return false; } } } } |
转自:http://www.cnblogs.com/goody9807/archive/2011/10/08/2202265.html
View Details