C#中C/S端实现WebService服务

 更新时间:2022年07月22日 14:40:59   作者:Menglon  
本文主要介绍了C#中C/S端实现WebService服务,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

使用 C#以B/S方式构建WebService服务十分简便,即是使用Asp.net在网站中添加WebService服务并使用IIS发布。但如需要在C/S程序中发布WebService服务则没有直接可用的类库。因此需要使用另外的方式实现WebService服务。

一、实现思路

WebService实际是使用Http并遵循SOAP协议格式进行交互。能够进行Http通讯即可实现WebService服务,只是没了现成的类库就需要自己编写解析SOAP格式数据包和组织应答包。

二、步骤

1.使用HttpListener构建服务

代码如下(示例):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Web;

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)
        {
            httpPostRequest.Prefixes.Add("http://" + HttpServerIP.ToString() + ":" + HttpServerPort.ToString() + "/");

            try
            { 
                httpPostRequest.Start();
            }
            catch(Exception ex)
            {
                string Mes = ex.Message;
            }

            Thread ThrednHttpPostRequest = new Thread(new ThreadStart(httpPostRequestHandle));
            ThrednHttpPostRequest.Start();
        }

        private void httpPostRequestHandle()
        {
            while (IsRun)
            {
                try
                { 
                    HttpListenerContext requestContext = httpPostRequest.GetContext();
                    Thread threadsub = new Thread(new ParameterizedThreadStart((requestcontext) =>
                    {
                        HttpListenerContext request = (HttpListenerContext)requestcontext;
                        //获取Post请求中的参数和值帮助类  
                        HttpListenerPostParaHelper httppost = new HttpListenerPostParaHelper(request);
                        //获取Post过来的参数和数据  
                        HttpListenerPostValue lst = httppost.GetHttpListenerPostValue();

                        byte[] buffer = null;
                        if (lst != null)
                        {
                            if(OnGetResponse != null)
                                buffer = OnGetResponse(lst);
                        }

                        if(buffer != null)
                        {//Response  
                            try
                            { 
                                request.Response.StatusCode = 200;
                                request.Response.Headers.Add("SOAPAction", "");
                                request.Response.Headers.Add("User-Agent", "gSOAP/2.8");
                                request.Response.ContentType = "text/xml; charset=utf-8";
                                request.Response.ContentEncoding = Encoding.UTF8;
                                request.Response.ContentLength64 = buffer.Length;
                                var output = request.Response.OutputStream;
                                output.Write(buffer, 0, buffer.Length);
                                output.Close();
                            }
                            catch(Exception ex2)
                            {
                            }
                        }
                        else
                        {
                            try
                            { 
                                request.Response.Close();
                            }
                            catch
                            { }
                        }
                    }));
                    threadsub.Start(requestContext);
                }
                catch (Exception ex)
                {
                    string Mes = ex.Message;
                }
            }
        }
        
        public void StopHttpThread()
        {
            IsRun = false;
            httpPostRequest.Abort();
        }
    }
}

启动服务后在httpPostRequestHandle()函数中编写对监听到的服务请求的处理。

//获取Post过来的参数和数据  
HttpListenerPostValue lst = httppost.GetHttpListenerPostValue();

GetHttpListenerPostValue();函数作用为取出请求中的数据部分和请求的名称。涉及到的类定义和代码如下:

/// <summary>  
    /// HttpListenner监听Post请求参数值实体  
    /// </summary>  
    public class HttpListenerPostValue
    {
        /// <summary>  
        /// 0=> 参数  
        /// 1=> 文件  
        /// </summary>  
        public int type = 0;
        /// <summary>
        /// 请求的类型名称
        /// </summary>
        public string name;
        /// <summary>
        /// 数据字符串
        /// </summary>
        public string datas;
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.IO;

namespace LadarManufacturabilityTooling
{
    /// <summary>  
    /// 获取Post请求中的参数和值帮助类  
    /// </summary>  
    public class HttpListenerPostParaHelper
    {
        private HttpListenerContext request;

        public HttpListenerPostParaHelper(HttpListenerContext request)
        {
            this.request = request;
        }

        /// <summary>  
        /// 获取Post过来的参数和数据  
        /// </summary>  
        /// <returns></returns>  
        public HttpListenerPostValue GetHttpListenerPostValue()
        {
            try
            {
                HttpListenerPostValue HttpListenerPostValueList = new HttpListenerPostValue();
                if (true)
                {
                    Stream body = request.Request.InputStream;
                    Encoding encoding = Encoding.UTF8;
                    StreamReader reader = new System.IO.StreamReader(body, encoding);
                    if (request.Request.ContentType != null)
                    {
                        Console.WriteLine("Client data content type {0}", request.Request.ContentType);
                    }
                    string datas = reader.ReadToEnd();
                    string Requestname = request.Request.RawUrl.Replace("/","");
                    HttpListenerPostValueList.datas = datas;
                    HttpListenerPostValueList.name = Requestname;
                    Console.WriteLine(datas);
                }
                return HttpListenerPostValueList;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}

以上部分和构建普通的http监听服务并无区别。

2.处理请求的数据

OnGetResponse事件用于处理请求的数据并组织回包

代码如下(示例):

private byte[] ThisHttpServic_OnGetResponse(HttpListenerPostValue Sender)
        {
            byte[] buffer = null;
            string restr = "";
            //处理收到的请求
            switch (Sender.name)
            {
                case "MyServiceName":
                {
                    string xmlOrgstr = "";
                    int iStartPos = Sender.datas.IndexOf("<xmlData>", 1);
                    int iStopPos = Sender.datas.IndexOf("</xmlData>", 1);
                    if (iStartPos > 0)
                    {
                        xmlOrgstr = Sender.datas.Substring(iStartPos + 9, iStopPos - iStartPos - 9);
                    }
                    string xmlstr = HttpUtility.HtmlDecode(xmlOrgstr);
                    string LOGIN_ACK = GetPack(xmlstr);
                    restr = GetCompleteSoapString(System.Security.SecurityElement.Escape(LOGIN_ACK));
                    break;
                }
                default:
                    restr = "";
                    break;
            }

            buffer = System.Text.Encoding.UTF8.GetBytes(restr);
            return buffer;
        }

需要从收到的http请求的数据部分提取出WebService服务的参数。

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:client1="http://LSCService.chinamobile.com" xmlns:service1="http://FSUService.chinamobile.com">

<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

<client1:invoke>

<xmlData>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;&lt;Request&gt;&lt;PK_Type&gt;&lt;Name&gt;LOGIN&lt;/Name&gt;&lt;/PK_Type&gt;&lt;Info&gt;&lt;UserName&gt;cmcc&lt;/UserName&gt;&lt;PassWord&gt;B101341CC2E4D6F5B395C7544B96A826&lt;/PassWord&gt;&lt;FSUID&gt;21202110060001&lt;/FSUID&gt;&lt;FSUIP&gt;192.168.1.253&lt;/FSUIP&gt;&lt;FSUMAC&gt;00:21:92:01:b5:9f&lt;/FSUMAC&gt;&lt;FSUVER&gt;2.0.0.15 for CMCC&lt;/FSUVER&gt;&lt;/Info&gt;&lt;/Request&gt;&#xD;&#xA;

</xmlData>

</client1:invoke><

/SOAP-ENV:Body>

</SOAP-ENV:Envelope>

收到的数据包原文(Sender.datas)为:

作为示例的服务的参数名为xmlData从SOAP中截取出参数的字符串进行处理。

由于xmlData中的内容是一串xml字符,SOAP传输时经过了转义,因此还需要转义回来。

string xmlstr = HttpUtility.HtmlDecode(xmlOrgstr);

处理完相应的业务,将需要回复的数据加上SOAP协议的头尾组好回复包返回。需要转义的部分记得进行符号转义。

System.Security.SecurityElement.Escape(LOGIN_ACK)

SOAP协议的头尾根据WebService服务函数的定义有所不同,需要自行组织。示例如下:

        /// <summary>
        /// 返回完整的SOAP包
        /// </summary>
        /// <param name="XmlData">应答部分</param>
        /// <returns></returns>
        public static string GetCompleteSoapString(string XmlData)
        {
            string restr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\""
            + " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\""
            + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
            + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
            + " xmlns:client1=\"http://LService.mobile.com\""
            + " xmlns:service1=\"http://FService.mobile.com\">"
            + "<SOAP-ENV:Body>"
            + "<client1:invokeResponse><invokeReturn>";
            string restrEnd = "</invokeReturn></client1:invokeResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>";
            restr = restr + XmlData + restrEnd;
            return restr;
        }

总结

既然C# 并未提供在C/S程序使用的WebService服务的.Net库,那么就使用HttpListener监听http请求自行解出其中的输入数据,再根据SOAP协议进行处理。以此方式实现WebService服务。

到此这篇关于C#中C/S端实现WebService服务的文章就介绍到这了,更多相关C# C/S端 WebService 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅析C# AsyncLocal如何在异步间进行数据流转

    浅析C# AsyncLocal如何在异步间进行数据流转

    在异步编程中,处理异步操作之间的数据流转是一个比较常用的操作,C#异步编程提供了一个强大的工具来解决这个问题,那就是AsyncLocal,下面我们就来看看AsyncLocal的原理和用法吧
    2023-08-08
  • WPF利用TabControl控件实现拖拽排序功能

    WPF利用TabControl控件实现拖拽排序功能

    在UI交互中,拖拽操作是一种非常简单友好的交互,这篇文章主要为大家介绍了WPF如何利用TabControl控件实现拖拽排序功能,需要的小伙伴可以参考一下
    2023-10-10
  • c#中executereader执行查询示例分享

    c#中executereader执行查询示例分享

    这篇文章主要介绍了c#中executereader执行查询示例,需要的朋友可以参考下
    2014-04-04
  • C#中如何利用正则表达式判断字符

    C#中如何利用正则表达式判断字符

    这篇文章主要介绍了C#中利用正则表达式判断字符的实例代码,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-12-12
  • C#实现简单的RSA非对称加密算法示例

    C#实现简单的RSA非对称加密算法示例

    这篇文章主要介绍了C#实现简单的RSA非对称加密算法,结合实例形式分析了C#实现RSA加密的具体步骤与相关操作技巧,需要的朋友可以参考下
    2017-08-08
  • C#调用AForge实现摄像头录像的示例代码

    C#调用AForge实现摄像头录像的示例代码

    这篇文章主要介绍了C#调用AForge实现摄像头录像的示例代码,非常具有实用价值,需要的朋友可以参考下
    2017-09-09
  • c#文件的I/O基本操作

    c#文件的I/O基本操作

    System.IO命名空间包含允许在数据流和文件上进行同步,异步及写入的类型,下面是关于c#文件的I/O基本操作讲解,需要的朋友可以参考下
    2014-03-03
  • C#队列的简单使用

    C#队列的简单使用

    队列的特性很简答,就是先进先出,一般利用数组来实现,本文就介绍了C#队列的简单使用,文中根据实例编码详细介绍的十分详尽,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • C# 中的IComparable和IComparer的使用及区别

    C# 中的IComparable和IComparer的使用及区别

    这篇文章主要介绍了C# 中的IComparable和IComparer的使用及区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • C#访问及调用类中私有成员与方法示例代码

    C#访问及调用类中私有成员与方法示例代码

    访问一个类的私有成员不是什么好做法,大家也都知道私有成员在外部是不能被访问的,这篇文章主要给大家介绍了关于C#访问及调用类中私有成员与方法的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2018-06-06

最新评论