Ajax calls handler and uses HttpWebRequest to access the WCF Service.
Introduction
With the popularization of mobile phones and mobile devices, mobile applications have also entered a boom. In the past, most PC portal websites also launched websites or apps that adapt to mobile devices, and even worse, they registered a public account. In mobile application development, I have learned the following solutions: 1. Original Ecological APP development; 2. JS + HTML websites compatible with mobile devices, set the cross-platform "vest"; 3. Mini-programs and public accounts (in fact, the shell is the same as the 2nd point ). Among them, JS + HTML applications occupy a majority. I have not counted and queried the relevant data in this proportion. There are a lot of such applications. In JS + HTML mobile development, most of the frameworks are WebService added to front-end pages. So let's talk about the topic today: ajax calls handler and uses HttpWebRequest to access the WCF Service. After talking about this, I want to show that mobile development is very popular now. Everyone uses the architecture of "JS + HTML + WebService + doll, I am sharing this article to provide a solution for everyone to develop in this architecture. It is still a big vernacular that suits me, but sometimes it is necessary to install and force it to blow the current Internet + era.
Body
To put it bluntly, mobile application development adopts the "JS + HTML + WebService + doll" architecture, which is referred to as this architecture below. The front-end uses JS (JQuery, React, etc) and HTML for rendering and business operations, and then request background service data through ajax, the server develops interfaces (WebService, WCF, etc.) in the form of APIs ).. In the. net platform, the server uses the wcf api, which is a good choice. For the sake of security, the server is generally not directly open to the client for direct calls. The customer must use the web server to call webservice in transit. The Intermediate program can be written only once. I use the general handler here.
First, the client calls handler through ajax:
Function Commit1 () {var req = {}; req. name = "Test 1"; req. age = "30"; var dvalue = JSON. stringify (req); var para = {action: "GetPersonDetail", data: dvalue}; ajaxWCFService (para, false, CommitSuc);} function CommitSuc (data) {data = $. parseJSON (data); alert ("Name:" + data. name + ", Age:" + data. age);} // call the service interface function ajaxWCFService (param, async, sucFunc) {var hUrl = document. URL; var pathName = document. location. pathname; var pos = hUrl. indexOf (pathName); var url = hUrl. substring (0, pos); url + = "/handle/BaseHandler. ashx "; $. ajax ({type: "post", url: url, data: param, async: async, success: sucFunc });}
Handler is used as a transit service and is only open to the website server. It is not open to the client. It accesses the server through HttpWebRequest. Here I use WCF:
Public void ProcessRequest (HttpContext context) {string action = context. request ["action"]; string Data = context. request ["data"]; // Data = "Name = testc & Age = 30"; string url =" http://localhost:28380/Service1.svc/ "+ Action; // get the message returned by the Server string result = postSend (url, Data); context. response. write (result);} public string postSend (string url, string param) {Encoding myEncode = Encoding. getEncoding ("UTF-8"); byte [] postBytes = Encoding. UTF8.GetBytes (param); HttpWebRequest req = (HttpWebRequest) HttpWebRequest. create (url); req. method = "POST"; req. contentType = "application/x-www-form-urlencoded; charset = UTF-8"; req. contentLength = postBytes. length; try {using (Stream reqStream = req. getRequestStream () {reqStream. write (postBytes, 0, postBytes. length);} using (WebResponse res = req. getResponse () {using (StreamReader reader = new StreamReader (res. getResponseStream () {string result = reader. readToEnd (); return result ;}} catch (WebException ex) {HttpWebResponse res = (HttpWebResponse) ex. response; StreamReader reader = new StreamReader (res. getResponseStream (); string result = reader. readToEnd (); string IsSucceed = "false"; string ErrorMsg = "Hander:" + ex. message + "StackTrace:" + ex. stackTrace + "\ r \ n ErrorResponse:" + result; var success = new {IsSucceed, ErrorMsg}; return JSONHelper. toJSON (success );}}
Then, the WCF server is first defined as a contract:
[OperationContract] [WebInvoke(UriTemplate = "GetPersonDetail", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] Stream GetPersonDetail(Stream req);
Implementation of the WCF method:
public Stream GetPersonDetail(Stream stream) { StreamReader sr = new StreamReader(stream); string s = sr.ReadToEnd(); sr.Dispose(); JObject jo = JObject.Parse(s); string Name = jo["Name"].ToString(); string Age = jo["Age"].ToString(); var result = new Person() { IsSucceed = true, Name = "Service Back:" + Name, Age = "Service Back:" + Age }; return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result))); }
At this point, the "JS + HTML + WebService + doll" framework is basically complete, and the next step is the work of adding bricks and mortar. You only need to write JS page operations and access to WCF data.
Now I will write this article today. If this article is helpful to you, please recommend it! Please refer to the source!