Preface
It is very easy to build a WebService service in B/S mode using C#, that is, add WebService services to the website and publish them using IIS. However, if you need to publish WebService services in C/S programs, there is no directly available class library. Therefore, it is necessary to implement WebService services in another way.
1. Implementation ideas
WebService is actually interacting with Http and following the SOAP protocol format. You can perform Http communication to implement WebService services, but without the ready-made class library, you need to write and parse SOAP format packets and organize the response packets yourself.
2. Steps
1. Build a service using HttpListener
The code is as follows (example):
using System; using ; using ; using ; using ; using ; using ; using ; namespace LadarManufacturabilityTooling { public class HttpServic { public delegate byte[] OnGetResponseDataHandle(HttpListenerPostValue Sender); public event OnGetResponseDataHandle OnGetResponse; private static HttpListener httpPostRequest = new HttpListener(); private static bool IsRun = true; public HttpServic(IPAddress HttpServerIP, int HttpServerPort) { ("http://" + () + ":" + () + "/"); try { (); } catch(Exception ex) { string Mes = ; } Thread ThrednHttpPostRequest = new Thread(new ThreadStart(httpPostRequestHandle)); (); } private void httpPostRequestHandle() { while (IsRun) { try { HttpListenerContext requestContext = (); Thread threadsub = new Thread(new ParameterizedThreadStart((requestcontext) => { HttpListenerContext request = (HttpListenerContext)requestcontext; //Get the parameters and values help class in the Post request HttpListenerPostParaHelper httppost = new HttpListenerPostParaHelper(request); //Get the parameters and data from Post HttpListenerPostValue lst = (); byte[] buffer = null; if (lst != null) { if(OnGetResponse != null) buffer = OnGetResponse(lst); } if(buffer != null) {//Response try { = 200; ("SOAPAction", ""); ("User-Agent", "gSOAP/2.8"); = "text/xml; charset=utf-8"; = Encoding.UTF8; .ContentLength64 = ; var output = ; (buffer, 0, ); (); } catch(Exception ex2) { } } else { try { (); } catch { } } })); (requestContext); } catch (Exception ex) { string Mes = ; } } } public void StopHttpThread() { IsRun = false; (); } } }
After starting the service, write the processing of the listened service request in the httpPostRequestHandle() function.
//Get the parameters and data from PostHttpListenerPostValue lst = ();
The GetHttpListenerPostValue(); function is used to fetch the data part in the request and the name of the request. The class definitions and codes involved are as follows:
/// <summary> /// HttpListenner listens to Post request parameter value entity /// </summary> public class HttpListenerPostValue { /// <summary> /// 0=> Parameters /// 1=> File /// </summary> public int type = 0; /// <summary> /// The requested type name /// </summary> public string name; /// <summary> /// Data string /// </summary> public string datas; }
using System; using ; using ; using ; using ; using ; using ; using ; namespace LadarManufacturabilityTooling { /// <summary> /// Get the parameters and values in the Post request help class /// </summary> public class HttpListenerPostParaHelper { private HttpListenerContext request; public HttpListenerPostParaHelper(HttpListenerContext request) { = request; } /// <summary> /// Get the parameters and data from Post /// </summary> /// <returns></returns> public HttpListenerPostValue GetHttpListenerPostValue() { try { HttpListenerPostValue HttpListenerPostValueList = new HttpListenerPostValue(); if (true) { Stream body = ; Encoding encoding = Encoding.UTF8; StreamReader reader = new (body, encoding); if ( != null) { ("Client data content type {0}", ); } string datas = (); string Requestname = ("/",""); = datas; = Requestname; (datas); } return HttpListenerPostValueList; } catch (Exception ex) { return null; } } } }
The above part is no different from building a normal http listening service.
2. Process the requested data
OnGetResponse event is used to process the requested data and organize the packet back
The code is as follows (example):
private byte[] ThisHttpServic_OnGetResponse(HttpListenerPostValue Sender) { byte[] buffer = null; string restr = ""; //Processing the received request switch () { case "MyServiceName": { string xmlOrgstr = ""; int iStartPos = ("<xmlData>", 1); int iStopPos = ("</xmlData>", 1); if (iStartPos > 0) { xmlOrgstr = (iStartPos + 9, iStopPos - iStartPos - 9); } string xmlstr = (xmlOrgstr); string LOGIN_ACK = GetPack(xmlstr); restr = GetCompleteSoapString((LOGIN_ACK)); break; } default: restr = ""; break; } buffer = .(restr); return buffer; }
The parameters of the WebService service need to be extracted from the data part of the received http request.
<?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="/soap/envelope/" xmlns:SOAP-ENC="/soap/encoding/" xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:xsd="http:///2001/XMLSchema" xmlns:client1="" xmlns:service1=""> <SOAP-ENV:Body SOAP-ENV:encodingStyle="/soap/encoding/"> <client1:invoke> <xmlData><?xml version="1.0" encoding="UTF-8" ?><Request><PK_Type><Name>LOGIN</Name></PK_Type><Info><UserName>cmcc</UserName><PassWord>B101341CC2E4D6F5B395C7544B96A826</PassWord><FSUID>21202110060001</FSUID><FSUIP>192.168.1.253</FSUIP><FSUMAC>00:21:92:01:b5:9f</FSUMAC><FSUVER>2.0.0.15 for CMCC</FSUVER></Info></Request>
 </xmlData> </client1:invoke>< /SOAP-ENV:Body> </SOAP-ENV:Envelope>
The original text of the received packet () is:
The parameter name of the service as an example is xmlData to intercept the string of the parameter from SOAP for processing.
Since the content in xmlData is a string of xml characters, SOAP is escaped during transmission, so it also needs to be escaped back.
string xmlstr = (xmlOrgstr);
After processing the corresponding service, return the reply packet by adding the data that needs to be replied to. Remember to symbolically escape the parts that need to be escaped.
(LOGIN_ACK)
The beginning and end of the SOAP protocol vary according to the definition of the WebService service function and needs to be organized by itself. Examples are as follows:
/// <summary> /// Return the complete SOAP package /// </summary> /// <param name="XmlData">Response section</param> /// <returns></returns> public static string GetCompleteSoapString(string XmlData) { string restr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"/soap/envelope/\"" + " xmlns:SOAP-ENC=\"/soap/encoding/\"" + " xmlns:xsi=\"http:///2001/XMLSchema-instance\"" + " xmlns:xsd=\"http:///2001/XMLSchema\"" + " xmlns:client1=\"\"" + " xmlns:service1=\"\">" + "<SOAP-ENV:Body>" + "<client1:invokeResponse><invokeReturn>"; string restrEnd = "</invokeReturn></client1:invokeResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>"; restr = restr + XmlData + restrEnd; return restr; }
Summarize
Since C# does not provide the .Net library of WebService service used in C/S programs, then use HttpListener to listen to http requests and solve the input data in it by yourself, and then process it according to the SOAP protocol. Implement WebService services in this way.
This is the article about the implementation of WebService services on C# in C#. For more related C# C/S WebService content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!