昨天在用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 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 Detailsusing System; using System.IO; using System.Net; using System.Text; using System.Web; namespace HP.Common { /// <summary> /// 信息 /// </summary> public class InfoCollect { /// <summary> /// 获取内网页面内容 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetPageByInner(string url) { return GetPage("http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + (HttpContext.Current.Request.ServerVariables["SERVER_PORT"] == "80" ? "" : ":" + HttpContext.Current.Request.ServerVariables["SERVER_PORT"]) + url); } /// <summary> /// 获取公网url内容(GET) /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetPage(string url) { return GetPage(url, "GET", null); } /// <summary> /// 获取公网url内容(Post方法) /// </summary> /// <param name="url"></param> […]
View Details任何程序都离不开对异常的处理,良好的异常处理方式可加快寻找出异常的根源,同时也需要避免暴露敏感信息到异常中。WCF这种典型的服务端和客户端交互的程序,服务端的异常更需要适当的处理。下面以一个简单的服务为例,说明WCF中处理异常的方式。 WCF服务定义如下,很明显方法Divide在divisor为0的时候将会抛出异常 View Code 客户端调用如下: using (var client = new CalculateServiceClient()) { try { Console.WriteLine(client.Divide(20, 0)); } catch (FaultException ex) { Console.WriteLine(ex.Reason); } } 首先需要知道的是,WCF的异常信息默认是以FaultException的形式返回到客户端,FaultException的关键属性Reason是对客户端反馈的最重要信息之一。以上客户端代码调用之后,默认的FaultException返回的Message信息如下: 由于内部错误,服务器无法处理该请求。有关该错误的详细信息,请打开服务器上的 IncludeExceptionDetailInFaults (从 ServiceBehaviorAttribute 或从 <serviceDebug> 配置行为)以便将异常信息发送回客户端,或在打开每个 Microsoft .NET Framework 3.0 SDK 文档的跟踪的同时检查服务器跟踪日志。 根据异常的提示,意思说如果要在客户端看到详细的Exception信息,那么请将ServiceBehavior对应的IncludeExceptionDetailInFaults属性设置为True,通常在配置中表现为如下设置: View Code 通过以上设置之后,客户端输出的内容为“尝试除以零”,这个提示信息跟原始的异常信息是一致,即返回的FaultException中的Reason包含原始异常的Message的值,但是这样处理之后服务端所报出的异常信息直接传到了客户端,比如一些保密信息也可能输出到了客户端,因此对于异常信息必须进行一个封装。最直接的形式莫过于在服务端就把异常给捕获了,并重新throw一个FaultException 服务端的代码改进如下,经过以下改进,那么客户端得到的信息仅仅是"操作失败",同时服务端也记录了异常信息(这时IncludeExceptionDetailInFaults是设置为False的)。 View Code 当然这是FaultException的默认用法,FaultException还支持强类型的异常错误信息,返回更加丰富和精确的错误提示。假设定义如下通用的一个FaultContract类型,将出错时的用户名和线程名字记录到异常信息中,因为异常信息也是通过SOAP格式传输的,因此跟定义其他DataContract的方式一样。 CommonFaultContract 那么服务方法的接口需要增加如下标记,如果不这样标记,那么客户端得到的异常类型依然是FaultException,而不是强类型的异常信息。 [FaultContract(typeof(CommonFaultContract))] int Divide(int dividend, int divisor) 实现方法中抛出异常的部分代码改成如下: 异常处理 这时候重新生成客户端的代理类,然后更新客户端的代码如下,红色部分即获取强类型的异常错误信息。 View Code 当然在具体应用中还需要根据需求,返回不同的信息,构建不同的FaultContract。 以上服务端捕获的异常方法,适用于方法比较少的情况,如果有十多个方法,一个个去写try catch然后做标记等,那么工作量会很大,而且代码也不利于重用。尝试寻找像MVC Controller那样的统一处理Exception的方式,将异常处理都放在基类中,那么只要继承与这个基类的方法都不需要去写try catch去捕获异常。但WCF中似乎没有这样的机制,放弃了这种做法。 最近在研究Enterprise Lib中对WCF的支持时,发现Exception Block中还特地有针对WCF程序异常处理的解决方案,而且满足以上说道的需求,即可记录异常,又可对异常信息进行封装。更重要的时,自动处理运行时的异常信息,不需要挨个方法的去写Try catch。秉承企业库的优秀传统,大部分工作还是通过配置就可以完成了,非常好的解决方案。下面介绍具体的使用步骤。 步骤一: 引用以下dll Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.dll Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.ObjectBuilder2.dll 步骤2: 在具体的实现类中,增加如下属性标记,其中WcfException为企业库中Exception Block中的一个异常处理策略,具体如何配置异常处理策略,请参考企业库的帮助文档。 [ExceptionShielding("WcfException")] public class CalculateService : ICalculateService 那么只要增加了[ExceptionShielding("WcfException")]这个属性标记之后,所有运行时的异常都将交给策略名为WcfException的异常处理block来处理,在这里就可以执行一些异常记录以及异常封装的操作。 步骤3: 将异常信息封装为FaultException,这个动作也是通过配置来完成。在Exception节点中添加一个Fault Contract Exception Handler。 Fault Contract Exception Handler需要设置以下两个属性值 exceptionMessage:所有异常封装后的错误信息 faultContractType:即返回异常的faltContract类型,这个类型必须指定一个,哪怕方法中没有用到也要,如果方法中有用到,那么客户端那边就能得到强类型FaultException,否则就是普通的FaultException。这里指定为之前定义的CommonFaultContract。 对于faultContract类型的值,还可以通过PropertyMappings来自定义需要从原始异常信息中映射到faultContract的属性中,这个属性可选。 […]
View Details使用WCF传输大数据时,我们都会碰到如题中出现的错误信息,出现这个问题是因为WCF本身的安全机制导致的,限制了客户端与服务器资源传输大小,那我们如何还解决这个问题呢? 针对这个问题,我们要分发送、接受两个方面来解决。 发送大数据:在WCF服务端解决 NetTcpBinding binding = new NetTcpBinding(); binding.MaxReceivedMessageSize= 2147483647(更改这个数字) ; 接受大数据:在WCF客户端解决 NetTcpBinding binding = new NetTcpBinding(); binding.ReaderQuotas = new XmlDictionaryReaderQuotas() { MaxStringContentLength = 2147483647(更改这个数字) }; 我们即可以使用如上述通过代码配置,我们同样也可以使用配置文件进行配置(在binding节中)。
1 2 3 4 5 6 7 |
public static System.ServiceModel.BasicHttpBinding Binding() { //读取 XML 数据时,超出最大字符串内容长度配额 (8192)。 System.ServiceModel.BasicHttpBinding bing = new System.ServiceModel.BasicHttpBinding(); bing.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxStringContentLength = 2147483647 }; //(更改这个数字) return bing; } |
1 2 3 |
public static API.iClient api = new API.iClient(Binding(), new System.ServiceModel.EndpointAddress("http://192.168.1.11:4417/WebService.svc")); 转自:<a href="http://www.cnblogs.com/Fooo/archive/2012/12/06/2805362.html">http://www.cnblogs.com/Fooo/archive/2012/12/06/2805362.html</a> |