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

一、创建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");
        }
    }
}

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

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

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

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

 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();
}

三、 动态调用服务

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();
}

原文地址:https://www.cnblogs.com/xubao/p/13559166.html