.net WebServer例
发布日期:2025-06-07 18:48:21
浏览次数:4
分类:精选文章
本文共 11162 字,大约阅读时间需要 37 分钟。
C# WebService 开发实例:ASMX 页面创建与功能实现
在实际开发中,创建一个功能完善的 ASMX 页面是一个常见任务。以下将详细介绍如何创建一个新的 ASMX 页面,并实现其核心功能。
1. ASMX 页面创建
首先,创建一个新的 ASMX 页面。使用 Visual Studio,创建一个新的 WebService项目,或者在现有项目中添加一个新的 ASMX 页面。页面命名可以按照功能命名规则进行,例如 AppService.asmx。
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;using System.Text;using System.Data;using System.Security.Cryptography;using System.Web.Script.Services;using System.IO;using System.Web.Script.Serialization;using DBUtility;using OAApp.Order;using System.IO.Compression;namespace OAApp{ ////// AppService 的摘要说明 /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 [System.Web.Script.Services.ScriptService] public class AppService : System.Web.Services.WebService { // string key = "";//钥匙 // BLL.Hotels hl= new BLL.Hotels() private readonly BLL.Hotels hl = new BLL.Hotels(); private readonly BLL.hotelcollect hc = new BLL.hotelcollect(); OAApp.TodayHY.HYModel.HY_iccard HY_iccard = new OAApp.TodayHY.HYModel.HY_iccard(); OAApp.TodayHY.HYBLL.HY_iccard BB = new OAApp.TodayHY.HYBLL.HY_iccard(); public static int[] EN_KEY = { 7, 2, 5, 4, 0, 1, 3, 6 }; public static int[] DE_KEY = { 4, 5, 1, 6, 3, 2, 7, 0 }; public static byte byteEncryption(byte nSrc) { byte nDst = 0; byte nBit = 0; int i; for (i = 0; i < 8; i++) { nBit = (byte)(1 << EN_KEY[i]); if ((nSrc & nBit) != 0) nDst |= (byte)(1 << i); } return nDst; } public static byte byteDecryption(byte nSrc) { byte nDst = 0; byte nBit = 0; int i; for (i = 0; i < 8; i++) { nBit = (byte)(1 << DE_KEY[i]); if ((nSrc & nBit) != 0) nDst |= (byte)(1 << i); } return nDst; } ////// 加密 /// /// ///public static string getCipherString(string source) { if (source.Trim() == "") { return ""; } string s = source; //byte[] sb = s.getBytes("UTF-8"); byte[] sb = Encoding.UTF8.GetBytes(s); //String d = new String(sb, "UTF-8"); string d = Encoding.UTF8.GetString(sb.ToArray()); //sb = d.getBytes("UTF-8"); sb = Encoding.UTF8.GetBytes(d); byte[] sbNew = new byte[sb.Length]; StringBuilder sbb = new StringBuilder(); for (int i = 0; i < sb.Length; i++) { byte t = byteEncryption(sb[i]); sbNew[i] = t; char c = (char)t; sbb.Append(c); } // String ss=new String(sbb.toString().getBytes("UTF-8"),"UTF-8"); return sbb.ToString(); } /// /// 解密 /// /// ///public static string Decrypt(string cipherString) { if (cipherString.Trim() == "") { return ""; } string drr = cipherString; byte[] drrByte = new byte[drr.Length]; for (int i = 0; i < drrByte.Length; i++) { //drrByte[i] = byteDecryption(Byte.valueOf((byte)drr.charAt(i))); drrByte[i] = byteDecryption( Convert.ToByte(drr[i])); } //String des = new String(drrByte, "UTF-8"); string des = Encoding.UTF8.GetString(drrByte.ToArray()); return des; } public string StrJtextConte() { string jtext = string.Empty; if ("POST" == System.Web.HttpContext.Current.Request.RequestType) { System.IO.Stream sm = System.Web.HttpContext.Current.Request.InputStream;//获取post正文 int len = (int)sm.Length;//post数据长度 byte[] inputByts = new byte[len];//字节数据,用于存储post数据 sm.Read(inputByts, 0, len);//将post数据写入byte数组中 sm.Close();//关闭IO流 jtext = Encoding.GetEncoding("unicode").GetString(inputByts);//转为unicode编码 jtext = Server.UrlDecode(jtext);//下面解释一下Server.UrlDecode和Server.UrlEncode的作用 } return jtext; } public string StrJtext() { string jtext = string.Empty; if ("POST" == System.Web.HttpContext.Current.Request.RequestType) { System.IO.Stream sm = System.Web.HttpContext.Current.Request.InputStream;//获取post正文 int len = (int)sm.Length;//post数据长度 byte[] inputByts = new byte[len];//字节数据,用于存储post数据 sm.Read(inputByts, 0, len);//将post数据写入byte数组中 sm.Close();//关闭IO流 jtext = Encoding.Default.GetString(inputByts);//转为unicode编码 jtext = Server.UrlDecode(jtext); } return jtext; } #region 设备注册 public struct ToJsonDeviceRegister { //属性的名字,必须与json格式字符串中的"key"值一样。 public string deviceCode { get; set; } //设备唯一编号 public string deviceType { get; set; }//设备类型(0:安卓 1:iOS) public string appId { get; set; }//应用ID(2961256) public string userId { get; set; }//注册用户ID public string pushUserId { get; set; }//推送用户ID(百度生成) public string channelId { get; set; }//通道ID(百度) public string iosDeviceToken { get; set; }//设备令牌 } /// /// 设备注册 /// /// 设备唯一编号 /// 设备类型(0:安卓 1:iOS) /// 应用ID(2961256) /// 注册用户ID /// 推送用户ID(百度生成) /// 通道ID(百度) /// 设备令牌 ///正常:{"resCode":1, " resMsg":"正常"}异常:{"resCode":0," resMsg":"未知错误"} [WebMethod(Description = "设备注册")] public string DeviceRegister() { string jtext = StrJtext();//获取数据 int res = 0; JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类 ToJsonDeviceRegister list = js.Deserialize(jtext); //将json数据转化为对象类型并赋值给list string dCode = Decrypt(list.deviceCode); int dType = Convert.ToInt32(Decrypt(list.deviceType)); string aoppid = Decrypt(list.appId); string userid = Decrypt(list.userId); string pushuserId = Decrypt(list.pushUserId); string channelid = Decrypt(list.channelId); string iosdevicetoken = Decrypt(list.iosDeviceToken); res= new BLL.deviceregister().AddDregisterInfo(dCode, dType, aoppid, userid, pushuserId, channelid, iosdevicetoken); return ReturnValue(res.ToString()); } #endregion}
2. 功能实现
2.1 加密与解密
在 WebService 中,数据加密与解密是核心安全功能之一。以下是实现的加密与解密方法。
public static byte byteEncryption(byte nSrc){ byte nDst = 0; byte nBit = 0; int i; for (i = 0; i < 8; i++) { nBit = (byte)(1 << EN_KEY[i]); if ((nSrc & nBit) != 0) nDst |= (byte)(1 << i); } return nDst;}public static byte byteDecryption(byte nSrc){ byte nDst = 0; byte nBit = 0; int i; for (i = 0; i < 8; i++) { nBit = (byte)(1 << DE_KEY[i]); if ((nSrc & nBit) != 0) nDst |= (byte)(1 << i); } return nDst;} 2.2 数据处理
在处理 POST 请求数据时,需要将二进制数据转换为 UTF-8 字符串。以下是实现的方法。
public string StrJtextConte(){ string jtext = string.Empty; if ("POST" == System.Web.HttpContext.Current.Request.RequestType) { System.IO.Stream sm = System.Web.HttpContext.Current.Request.InputStream; int len = (int)sm.Length; byte[] inputByts = new byte[len]; sm.Read(inputByts, 0, len); sm.Close(); jtext = Encoding.GetEncoding("unicode").GetString(inputByts); jtext = Server.UrlDecode(jtext); } return jtext;} 2.3 设备注册
设备注册是 WebService 的一个重要功能,需要处理 JSON 格式的请求并返回相应的响应。
public string DeviceRegister(){ string jtext = StrJtext(); int res = 0; JavaScriptSerializer js = new JavaScriptSerializer(); ToJsonDeviceRegister list = js.Deserialize (jtext); string dCode = Decrypt(list.deviceCode); int dType = Convert.ToInt32(Decrypt(list.deviceType)); string aoppid = Decrypt(list.appId); string userid = Decrypt(list.userId); string pushuserId = Decrypt(list.pushUserId); string channelid = Decrypt(list.channelId); string iosdevicetoken = Decrypt(list.iosDeviceToken); res = new BLL.deviceregister().AddDregisterInfo(dCode, dType, aoppid, userid, pushuserId, channelid, iosdevicetoken); return ReturnValue(res.ToString());} 2.4 返回值处理
返回值需要以 JSON 格式返回,以下是实现的方法。
public static string ReturnValue(string res){ StringBuilder JsonString = new StringBuilder(); if (Convert.ToInt32(res) > 0) { JsonString.Append("{ "); JsonString.Append("\"resCode\":"); JsonString.Append("\"1\","); JsonString.Append("\"resMsg\":"); JsonString.Append("\"正确\""); JsonString.Append("}"); return JsonString.ToString(); } else { JsonString.Append("{ "); JsonString.Append("\"resCode\":"); JsonString.Append("\"0\","); JsonString.Append("\"resMsg\":"); JsonString.Append("\"未知错误\""); JsonString.Append("}"); return JsonString.ToString(); }} 3. 调用说明
以下是如何在页面中调用 WebService 的示例。
protected void Page_Load(object sender, EventArgs e){ string result = BuildRequest("http://175.6.7.245:8007/AppService.asmx/UserMobileWebPayValidate", Server.UrlEncode("{\"orderId\":\"wx444201411111611\"}"), "UTF-8"); Response.Write(result);}public static string BuildRequest(string strUrl, string strRequestData, string _input_charset){ Encoding code = Encoding.GetEncoding(_input_charset); byte[] bytesRequestData = code.GetBytes(strRequestData); HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl); myReq.Method = "post"; myReq.ContentType = "application/x-www-form-urlencoded"; myReq.ContentLength = bytesRequestData.Length; Stream requestStream = myReq.GetRequestStream(); requestStream.Write(bytesRequestData, 0, bytesRequestData.Length); requestStream.Close(); HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse(); Stream myStream = HttpWResp.GetResponseStream(); StreamReader reader = new StreamReader(myStream, code); StringBuilder responseData = new StringBuilder(); string line; while ((line = reader.ReadLine()) != null) { responseData.Append(line); } strResult = responseData.ToString(); myStream.Close(); reader.Close(); System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); xml.LoadXml(strResult); strResult = xml.ChildNodes[1].InnerText; return strResult;} 4. 总结
通过以上步骤,可以实现一个功能完善的 ASMX 页面。从创建服务到实现各项功能,整个过程需要结合实际项目需求进行调整和优化。希望以上内容能为您的开发提供参考和帮助!
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2026年06月01日 15时16分00秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
php查最大值,在PHP数组中查找最大值
2023-03-01
php根据年月日计算年龄
2023-03-01
RabbitMQ - 单机部署(超详细)
2023-03-01
php检查注册,PHP检查注册的电子邮件地址是一个’school.edu’地址
2023-03-01
php模拟发送GET和POST请求
2023-03-01
RabbitMQ - 以 MQ 为例,手写一个 RPC 框架 demo
2023-03-01
php模板引擎smarty
2023-03-01
php正则表达式模式
2023-03-01
php正则表达式的特殊字符含义
2023-03-01
PHP正则表达式获取武汉市的实时pm2.5数据并邮件发送phpmailer
2023-03-01
RabbitMQ + JMeter组合,优化你的中间件处理方式!
2023-03-01
PHP水仙花问题解法之一
2023-03-01
php没有解析是怎么回事,linux下php文件没有被剖析怎么办?_后端开发
2023-03-01
php注册页面实现注册后跳转页面
2023-03-01
PHP消息队列的实现方式与详解,值得一看
2023-03-01
PHP混合Go协程并发
2023-03-01
php源码中如何添加滚动公告,给WordPress网站添加滚动公告的方法
2023-03-01
PHP源码安装后如何新增模块
2023-03-01
php源码详细安装步骤,linux下php源码安装步骤
2023-03-01