当前位置: 首页 > news >正文

Html前后端Ajax交互数据前端JavaScript脚本后台C#ashx服务

本示例使用设备:https://item.taobao.com/item.htm?spm=a21dvs.23580594.0.0.52de2c1bU8Fdbo&ft=t&id=615391857885

前端以GET模式向后台请求数据 

   function MyGetAjax() {var xhr = new XMLHttpRequest();xhr.open('GET', 'http://192.168.1.211/HttpReader.ashx?commandname=piccreadex&commanddata=170000000001FFFFFFFFFFFF', true);xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xhr.onreadystatechange = function() {if (xhr.readyState === 4 && xhr.status === 200) {var response = xhr.responseText;console.log(response);} else {alert("获取服务端的读卡指令失败!");}};xhr.send();}

前端以POST模式向后台请求数据 

   function MyPostAjax(){var xhr = new XMLHttpRequest()xhr.onreadystatechange = function(){if (this.readyState == 4) {if (this.status == 200) {console.log(xhr.responseText)var obj = JSON.parse(xhr.responseText);console.log(obj.Code);console.log(obj.Msg);console.log(obj.Data);} else {alert("获取服务端的读卡指令失败!");}}}xhr.open("POST", "http://192.168.1.211/ReaderAPI.ashx", true)xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xhr.send("commandname=piccreadex&commanddata=170000000001FFFFFFFFFFFF")}

Http协议读卡器: https://item.taobao.com/item.htm?spm=a21dvs.23580594.0.0.52de2c1bVrFWxY&ft=t&id=22173428704

服务端C#接收客户端发送的请求,并将数据加密后回应给客户端

<%@ WebHandler Language="C#" Class="ReaderAPI" %>using System;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Text;public class ReaderAPI : IHttpHandler
{private static readonly byte[] Key = Encoding.UTF8.GetBytes("GuangzhouRongShiElectron"); // 3DES 24字节密钥,长度必须=24private static readonly byte[] IV = Encoding.UTF8.GetBytes("3DESEncr");                  // 3DES 8字节初始化向量,长度必须=8,如使用3DES加密需将这两个参数下传到发卡器上public void ProcessRequest(HttpContext context){                string commandname = "";    //指令名称string commanddata = "";    //指令代码context.Response.ContentType = "text/plain";context.Response.Headers.Add("Access-Control-Allow-Origin", "*");       //表示支持跨源交互数据if (context.Request["commandname"] != null) { commandname = context.Request["commandname"].ToString(); }if (context.Request["commanddata"] != null) { commanddata = context.Request["commanddata"].ToString(); }if (commandname == "" && commanddata == "")    //如果未接收到有效的Request信息,再尝试用Json解析是否有Request信息{StreamReader sr = new StreamReader(context.Request.GetBufferlessInputStream());string response = sr.ReadToEnd();commandname = getjsonval(response, "commandname");commanddata = getjsonval(response, "commanddata");}string jsonText = "{\"Response\":\"json\"";switch (commandname){case "piccreadex":if (HexToAscii(commanddata) == ""){jsonText = jsonText + ",\"Code\":\"1002\"" + ",\"Msg\":\"" + "Parameter error\"" + ",\"Data\":\"null\"}";}else{string desstr = TripleDESEncrypt(HexToAscii(commanddata));jsonText = jsonText + ",\"Code\":\"" + "0\"";jsonText = jsonText + ",\"Msg\":\"" + "Successful\"";jsonText = jsonText + ",\"Data\":\"" + desstr + "\"}";}                break;case "1":jsonText = jsonText + ",\"Code\":\"" + "0\"";jsonText = jsonText + ",\"Msg\":\"" + "Successful\"";jsonText = jsonText + ",\"Data\":\"1234567890\"}";break;default:jsonText = jsonText + ",\"Code\":\"" + "1001\"";jsonText = jsonText + ",\"Msg\":\"" + "Invalid request\"";jsonText = jsonText + ",\"Data\":\"null\"}";break;}context.Response.ContentType = "application/json";context.Response.Write(jsonText);}//16进制字符串转ASC码======================================================================================public static string HexToAscii(string hexString){string asciiString = "";try{int hexlen = hexString.Length / 2;byte[] byteArray = new byte[hexlen];for (int i = 0; i < hexlen; i++){byteArray[i] = Convert.ToByte(Convert.ToInt32(hexString.Substring(i * 2, 2), 16));}System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();asciiString = asciiEncoding.GetString(byteArray);            }catch{asciiString = "";}return asciiString;}//3DES加密===================================================================================================public static string TripleDESEncrypt(string data){using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider()){des.Key = Key;des.IV = IV;ICryptoTransform encrytor = des.CreateEncryptor();using (MemoryStream ms = new MemoryStream()){using (CryptoStream cs = new CryptoStream(ms, encrytor, CryptoStreamMode.Write)){using (StreamWriter sw = new StreamWriter(cs)){sw.Write(data);}}return Convert.ToBase64String(ms.ToArray());}}}//解析JSON数据==================================================================================================public static string getjsonval(string totalstr, string namestr)    {string valustr = "";totalstr = totalstr.Replace("{", "");totalstr = totalstr.Replace("}", "");totalstr = totalstr.Replace("\"", "");string[] dataArray = totalstr.Split(new char[2] { ',', ',' });if (dataArray.GetUpperBound(0) > 0){for (int i = 0; i < dataArray.Length; i++){string[] dataArray2 = dataArray[i].Split(new char[2] { ':', ':' });if (dataArray2[0] == namestr){valustr = dataArray2[1];break;}}}return valustr;}public bool IsReusable{get{return false;}}}

http://www.lryc.cn/news/490971.html

相关文章:

  • 问:Spring Boot应用监控组件工具,梳理一下?
  • 利用Hooka开源的多种功能shellcode加载器实现快速免杀火绒,静态360+360杀毒,微步查杀1,vt查杀7(教程)
  • 2025-2026财年美国CISA国际战略规划(下)
  • iframe通过url方式来获传递的参数
  • 蓝桥杯不知道叫什么题目
  • 最多可收集的水果数目
  • 戴尔 AI Factory 上的 Agentic RAG 搭载 NVIDIA 和 Elasticsearch 向量数据库
  • HarmonyOS4+NEXT星河版入门与项目实战(16)------ 状态管理 @State(页面数据刷新与渲染)
  • Origin教程003:数据导入(2)-从文件导入和导入矩阵数据
  • 设计自己的网络通信协议
  • 深入理解 Seata:分布式事务的最佳解决方案
  • JDK下载
  • 如何使用 Python 开发一个简单的文本数据转换为 Excel 工具
  • React(六)——Redux
  • java抽奖系统(二)
  • STM32F10x 定时器
  • 从0开始学PHP面向对象内容之常用设计模式(适配器,桥接,装饰器)
  • 玩转数字与运算:用C语言实现24点游戏的扑克牌魅力
  • 前端入门之VUE--基础与核心
  • logback 初探学习
  • 在Elasticsearch中,是怎么根据一个词找到对应的倒排索引的?
  • 1992-2021年 各省市县经过矫正的夜间灯光数据(GNLD、VIIRS)区域汇总:省份、城市、区县面板数据
  • linux实战-黑链——玄机靶场
  • 鸿蒙NEXT开发案例:字数统计
  • uniapp vue2项目迁移vue3项目
  • 16.C++STL 3(string类的模拟,深浅拷贝问题)
  • 神经网络10-Temporal Fusion Transformer (TFT)
  • “iOS profile文件与私钥证书文件不匹配”总结打ipa包出现的问题
  • 《图像梯度与常见算子全解析:原理、用法及效果展示》
  • 【c++篇】:探索c++中的std::string类--掌握字符串处理的精髓