本文共 11162 字,大约阅读时间需要 37 分钟。
在实际开发中,创建一个功能完善的 ASMX 页面是一个常见任务。以下将详细介绍如何创建一个新的 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}
在 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;}
在处理 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;}
设备注册是 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());}
返回值需要以 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(); }}
以下是如何在页面中调用 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;}
通过以上步骤,可以实现一个功能完善的 ASMX 页面。从创建服务到实现各项功能,整个过程需要结合实际项目需求进行调整和优化。希望以上内容能为您的开发提供参考和帮助!
转载地址:http://zirfk.baihongyu.com/