C#调用WebService服务(动态调用)

摘要:
添加服务引用后,ServiceReferences和app。config添加到项目解决方案中,如下图所示。ServiceReference1是上面添加的服务,app。config是服务配置文件,app。config中的配置大致如下。当服务地址更改时,只需修改端点中的地址即可。˃˃configuration˃客户端调用WebService//,结果如图所示。staticvoidMain{ServiceReference1.Service1SoapClient=newServiceReference1。Service1SoapClient()//调用服务stringhello=client的HelloWorld方法。HelloWorld();安慰写入行;//调用服务的Add方法inta=1,b=2;intadd=客户端。添加(a,b);安慰写入行;//调用服务stringdate=client的GetDate方法。获取日期();安慰WriteLine;安慰ReadKey();}3、 动态调用serviceusingSystem;使用系统。CodeDom;使用System.CodeDom。编译器;使用系统。IO;使用系统。网使用系统。反射使用System.Web.Services。描述使用Microsoft。CSharp;StaticvoidMain{//服务地址可以放在程序的配置文件中。这样,即使服务地址更改,也不需要重新编译程序。

一、创建WebService

using System;
using System.Web.Services;
 
namespace WebService1
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/", Description="测试服务")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
 
        [WebMethod(Description="Hello World")]
        public string HelloWorld()
        {
            return "Hello World";
        }
 
        [WebMethod(Description="A加B")]
        public int Add(int a, int b)
        {
            return a + b;
        }
 
        [WebMethod(Description="获取时间")]
        public string GetDate()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }
}

服务创建后,在浏览器中输入服务地址,可以看到如下图所示。

C#调用WebService服务(动态调用)第1张

 二、通过Visual Studio添加服务引用

    通过Visual Studio添加服务引用相当方便,只需要在Visual Studio中选择添加服务引用,便可以生成代理类,在项目中通过代理调用服务,如下图所示。

C#调用WebService服务(动态调用)第2张

 添加服务引用以后,在项目解决方案中多了Service References和app.config,如下图所示。

C#调用WebService服务(动态调用)第3张

 ServiceReference1就是上面添加的服务,app.config是服务的配置文件,app.config里面的配置大致如下,当服务地址改变时,修改endpoint里的address即可。

<!--app.config文件配置-->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="Service1Soap" closeTimeout="00:01:00" openTimeout="00:01:00"
                    receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
                    bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:19951/Service1.asmx" binding="basicHttpBinding"
                bindingConfiguration="Service1Soap" contract="ServiceReference1.Service1Soap"
                name="Service1Soap" />
        </client>
    </system.serviceModel>
</configuration>

客户端调用WebService

//调用服务,结果如图所示。
static void Main(string[] args)
{
    ServiceReference1.Service1SoapClient client = new ServiceReference1.Service1SoapClient();
 
    //调用服务的HelloWorld方法
    string hello = client.HelloWorld();
    Console.WriteLine("调用服务HelloWorld方法,返回{0}", hello);
 
    //调用服务的Add方法
    int a = 1, b = 2;
    int add = client.Add(a, b);
    Console.WriteLine("调用服务Add方法,{0} + {1} = {2}", a, b, add);
 
    //调用服务的GetDate方法
    string date = client.GetDate();
    Console.WriteLine("调用服务GetDate方法,返回{0}", date);
 
    Console.ReadKey();
}

C#调用WebService服务(动态调用)第4张

三、 动态调用服务

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Net;
using System.Reflection;
using System.Web.Services.Description;
using Microsoft.CSharp;
 
static void Main(string[] args)
{
    //服务地址,该地址可以放到程序的配置文件中,这样即使服务地址改变了,也无须重新编译程序。
    string url = "http://localhost:19951/Service1.asmx";
 
    //客户端代理服务命名空间,可以设置成需要的值。
    string ns = string.Format("ProxyServiceReference");
 
    //获取WSDL
    WebClient wc = new WebClient();
    Stream stream = wc.OpenRead(url + "?WSDL");
    ServiceDescription sd = ServiceDescription.Read(stream);//服务的描述信息都可以通过ServiceDescription获取
    string classname = sd.Services[0].Name;
 
    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
    sdi.AddServiceDescription(sd, "", "");
    CodeNamespace cn = new CodeNamespace(ns);
 
    //生成客户端代理类代码
    CodeCompileUnit ccu = new CodeCompileUnit();
    ccu.Namespaces.Add(cn);
    sdi.Import(cn, ccu);
    CSharpCodeProvider csc = new CSharpCodeProvider();
 
    //设定编译参数
    CompilerParameters cplist = new CompilerParameters();
    cplist.GenerateExecutable = false;
    cplist.GenerateInMemory = true;
    cplist.ReferencedAssemblies.Add("System.dll");
    cplist.ReferencedAssemblies.Add("System.XML.dll");
    cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
    cplist.ReferencedAssemblies.Add("System.Data.dll");
 
    //编译代理类
    CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
    if (cr.Errors.HasErrors == true)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
        {
            sb.Append(ce.ToString());
            sb.Append(System.Environment.NewLine);
        }
        throw new Exception(sb.ToString());
    }
 
    //生成代理实例,并调用方法
    Assembly assembly = cr.CompiledAssembly;
    Type t = assembly.GetType(ns + "." + classname, true, true);
    object obj = Activator.CreateInstance(t);
 
 
    
    //调用HelloWorld方法
    MethodInfo helloWorld = t.GetMethod("HelloWorld");
    object helloWorldReturn = helloWorld.Invoke(obj, null);
    Console.WriteLine("调用HelloWorld方法,返回{0}", helloWorldReturn.ToString());
 
    //获取Add方法的参数
    ParameterInfo[] helloWorldParamInfos = helloWorld.GetParameters();
    Console.WriteLine("HelloWorld方法有{0}个参数:", helloWorldParamInfos.Length);
    foreach (ParameterInfo paramInfo in helloWorldParamInfos)
    {
        Console.WriteLine("参数名:{0},参数类型:{1}", paramInfo.Name, paramInfo.ParameterType.Name);
    }
 
    //获取HelloWorld返回的数据类型
    string helloWorldReturnType = helloWorld.ReturnType.Name;
    Console.WriteLine("HelloWorld返回的数据类型是{0}", helloWorldReturnType);
    
 
    
    Console.WriteLine("
==============================================================");    
    //调用Add方法
    MethodInfo add = t.GetMethod("Add");
    int a = 10, b = 20;//Add方法的参数
    object[] addParams = new object[]{a, b};
    object addReturn = add.Invoke(obj, addParams);
    Console.WriteLine("调用HelloWorld方法,{0} + {1} = {2}", a, b, addReturn.ToString());
 
    //获取Add方法的参数
    ParameterInfo[] addParamInfos = add.GetParameters();
    Console.WriteLine("Add方法有{0}个参数:", addParamInfos.Length);
    foreach (ParameterInfo paramInfo in addParamInfos)
    {
        Console.WriteLine("参数名:{0},参数类型:{1}", paramInfo.Name, paramInfo.ParameterType.Name);
    }
 
    //获取Add返回的数据类型
    string addReturnType = add.ReturnType.Name;
    Console.WriteLine("Add返回的数据类型:{0}", addReturnType);
 
 
    
    Console.WriteLine("
==============================================================");    
    //调用GetDate方法
    MethodInfo getDate = t.GetMethod("GetDate");
    object getDateReturn = getDate.Invoke(obj, null);
    Console.WriteLine("调用GetDate方法,返回{0}", getDateReturn.ToString());
 
    //获取GetDate方法的参数
    ParameterInfo[] getDateParamInfos = getDate.GetParameters();
    Console.WriteLine("GetDate方法有{0}个参数:", getDateParamInfos.Length);
    foreach (ParameterInfo paramInfo in getDateParamInfos)
    {
        Console.WriteLine("参数名:{0},参数类型:{1}", paramInfo.Name, paramInfo.ParameterType.Name);
    }
 
    //获取Add返回的数据类型
    string getDateReturnType = getDate.ReturnType.Name;
    Console.WriteLine("GetDate返回的数据类型:{0}", getDateReturnType);
    
 
    Console.WriteLine("

==============================================================");
    Console.WriteLine("服务信息");
    Console.WriteLine("服务名称:{0},服务描述:{1}", sd.Services[0].Name, sd.Services[0].Documentation);
    Console.WriteLine("服务提供{0}个方法:", sd.PortTypes[0].Operations.Count);
    foreach (Operation op in sd.PortTypes[0].Operations)
    {
        Console.WriteLine("方法名称:{0},方法描述:{1}", op.Name, op.Documentation);
    }            
 
    Console.ReadKey();
}

C#调用WebService服务(动态调用)第5张

免责声明:文章转载自《C#调用WebService服务(动态调用)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Mac安装JMeter时Unable to access jarfile ./ApacheJMeter.jar 解决方法杭州选房的一些小建议(转)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

guava API整理

1,大纲 让我们来熟悉瓜娃,并体验下它的一些API,分成如下几个部分: Introduction Guava Collection API Guava Basic Utilities IO API Cache API 2,为神马选择瓜娃? 瓜娃是java API蛋糕上的冰激凌(精华) 高效设计良好的API. 被google的开发者设计,实现和使用。...

shell脚本中if的“-e,-d,-f”

文件表达式-e filename 如果 filename存在,则为真-d filename 如果 filename为目录,则为真-f filename 如果 filename为常规文件,则为真-L filename 如果 filename为符号链接,则为真-r filename 如果 filename可读,则为真-w filename 如果 filenam...

(转载)Telnet协议详解及使用C# 用Socket 编程来实现Telnet协议

转自:http://www.cnblogs.com/jicheng1014/archive/2010/01/28/1658793.html 这因为有个任务涉及到使用telnet 来连接远端的路由器,获取信息,之后进行处理. 所以需要写一个自动telnet登录到远端,之后获取信息进行处理的程序. 自己C++ 一塌糊涂,所以几乎最开始就没打算用C++或者C写...

c++之标准库iomanip

C++ 标准库之iomanip istream & istream::get(char *, int, char = ‘ ’); istream & istream::getline(char *, int, char = ‘ ’); 作用: 从文本中提取指定个数的字符串, 并在串数组末尾添加一个空字符. 区别: get() 不从流中提取终...

Kafka长文总结

Kafka是目前使用较多的消息队列,以高吞吐量得到广泛使用 特点: 1、同时为发布和订阅提供搞吞吐量。Kafka的设计目标是以时间复杂度为O(1)的方式提供消息持久化能力的,即使对TB级别以上数据也能保证常数时间的访问性能,即使在非常廉价的商用机器上也能做到单机支持每秒100K条消息的传输(一般消息处理是百万级,使用Partition实现机器间的并行处理)...

【json的处理】二、Jackson的处理

目前处理json的方法有很多,这里主要总结四种方法 1. Gson方式处理json 【json的处理】一、Gson处理 2. FastJson方式处理json 【json的处理】三、FastJson的处理 3. Jackson方式处理json 【json的处理】二、Jackson的处理 4. json-flattener方式处理json 【json的处理】...