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

1 创建WebService

[csharp]  view plain  copy
  1. using System;  
  2. using System.Web.Services;  
  3.   
  4. namespace WebService1  
  5. {  
  6.     /// <summary>  
  7.     /// Service1 的摘要说明  
  8.     /// </summary>  
  9.     [WebService(Namespace = "http://tempuri.org/", Description="测试服务")]  
  10.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  11.     [System.ComponentModel.ToolboxItem(false)]  
  12.     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。  
  13.     [System.Web.Script.Services.ScriptService]  
  14.     public class Service1 : System.Web.Services.WebService  
  15.     {  
  16.   
  17.         [WebMethod(Description="Hello World")]  
  18.         public string HelloWorld()  
  19.         {  
  20.             return "Hello World";  
  21.         }  
  22.   
  23.         [WebMethod(Description="A加B")]  
  24.         public int Add(int a, int b)  
  25.         {  
  26.             return a + b;  
  27.         }  
  28.   
  29.         [WebMethod(Description="获取时间")]  
  30.         public string GetDate()  
  31.         {  
  32.             return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");  
  33.         }  
  34.     }  
  35. }  

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



2 通过Visual Studio添加服务引用

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




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



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

[html]  view plain  copy
  1. <!--app.config文件配置-->  
  2. <?xml version="1.0" encoding="utf-8" ?>  
  3. <configuration>  
  4.     <configSections>  
  5.     </configSections>  
  6.     <system.serviceModel>  
  7.         <bindings>  
  8.             <basicHttpBinding>  
  9.                 <binding name="Service1Soap" closeTimeout="00:01:00" openTimeout="00:01:00"  
  10.                     receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"  
  11.                     bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"  
  12.                     maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"  
  13.                     messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"  
  14.                     useDefaultWebProxy="true">  
  15.                     <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"  
  16.                         maxBytesPerRead="4096" maxNameTableCharCount="16384" />  
  17.                     <security mode="None">  
  18.                         <transport clientCredentialType="None" proxyCredentialType="None"  
  19.                             realm="" />  
  20.                         <message clientCredentialType="UserName" algorithmSuite="Default" />  
  21.                     </security>  
  22.                 </binding>  
  23.             </basicHttpBinding>  
  24.         </bindings>  
  25.         <client>  
  26.             <endpoint address="http://localhost:19951/Service1.asmx" binding="basicHttpBinding"  
  27.                 bindingConfiguration="Service1Soap" contract="ServiceReference1.Service1Soap"  
  28.                 name="Service1Soap" />  
  29.         </client>  
  30.     </system.serviceModel>  
  31. </configuration>  

客户端调用WebService

[csharp]  view plain  copy
  1. //调用服务,结果如图所示。  
  2. static void Main(string[] args)  
  3. {  
  4.     ServiceReference1.Service1SoapClient client = new ServiceReference1.Service1SoapClient();  
  5.   
  6.     //调用服务的HelloWorld方法  
  7.     string hello = client.HelloWorld();  
  8.     Console.WriteLine("调用服务HelloWorld方法,返回{0}", hello);  
  9.   
  10.     //调用服务的Add方法  
  11.     int a = 1, b = 2;  
  12.     int add = client.Add(a, b);  
  13.     Console.WriteLine("调用服务Add方法,{0} + {1} = {2}", a, b, add);  
  14.   
  15.     //调用服务的GetDate方法  
  16.     string date = client.GetDate();  
  17.     Console.WriteLine("调用服务GetDate方法,返回{0}", date);  
  18.   
  19.     Console.ReadKey();  
  20. }  



3 动态调用服务(转自http://www.cnblogs.com/prolifes/articles/1235685.html)

[csharp]  view plain  copy
  1. using System;  
  2. using System.CodeDom;  
  3. using System.CodeDom.Compiler;  
  4. using System.IO;  
  5. using System.Net;  
  6. using System.Reflection;  
  7. using System.Web.Services.Description;  
  8. using Microsoft.CSharp;  
  9.   
  10. static void Main(string[] args)  
  11. {  
  12.     //服务地址,该地址可以放到程序的配置文件中,这样即使服务地址改变了,也无须重新编译程序。  
  13.     string url = "http://localhost:19951/Service1.asmx";  
  14.   
  15.     //客户端代理服务命名空间,可以设置成需要的值。  
  16.     string ns = string.Format("ProxyServiceReference");  
  17.   
  18.     //获取WSDL  
  19.     WebClient wc = new WebClient();  
  20.     Stream stream = wc.OpenRead(url + "?WSDL");  
  21.     ServiceDescription sd = ServiceDescription.Read(stream);//服务的描述信息都可以通过ServiceDescription获取  
  22.     string classname = sd.Services[0].Name;  
  23.   
  24.     ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();  
  25.     sdi.AddServiceDescription(sd, """");  
  26.     CodeNamespace cn = new CodeNamespace(ns);  
  27.   
  28.     //生成客户端代理类代码  
  29.     CodeCompileUnit ccu = new CodeCompileUnit();  
  30.     ccu.Namespaces.Add(cn);  
  31.     sdi.Import(cn, ccu);  
  32.     CSharpCodeProvider csc = new CSharpCodeProvider();  
  33.   
  34.     //设定编译参数  
  35.     CompilerParameters cplist = new CompilerParameters();  
  36.     cplist.GenerateExecutable = false;  
  37.     cplist.GenerateInMemory = true;  
  38.     cplist.ReferencedAssemblies.Add("System.dll");  
  39.     cplist.ReferencedAssemblies.Add("System.XML.dll");  
  40.     cplist.ReferencedAssemblies.Add("System.Web.Services.dll");  
  41.     cplist.ReferencedAssemblies.Add("System.Data.dll");  
  42.   
  43.     //编译代理类  
  44.     CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);  
  45.     if (cr.Errors.HasErrors == true)  
  46.     {  
  47.         System.Text.StringBuilder sb = new System.Text.StringBuilder();  
  48.         foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)  
  49.         {  
  50.             sb.Append(ce.ToString());  
  51.             sb.Append(System.Environment.NewLine);  
  52.         }  
  53.         throw new Exception(sb.ToString());  
  54.     }  
  55.   
  56.     //生成代理实例,并调用方法  
  57.     Assembly assembly = cr.CompiledAssembly;  
  58.     Type t = assembly.GetType(ns + "." + classname, truetrue);  
  59.     object obj = Activator.CreateInstance(t);  
  60.   
  61.   
  62.       
  63.     //调用HelloWorld方法  
  64.     MethodInfo helloWorld = t.GetMethod("HelloWorld");  
  65.     object helloWorldReturn = helloWorld.Invoke(obj, null);  
  66.     Console.WriteLine("调用HelloWorld方法,返回{0}", helloWorldReturn.ToString());  
  67.   
  68.     //获取Add方法的参数  
  69.     ParameterInfo[] helloWorldParamInfos = helloWorld.GetParameters();  
  70.     Console.WriteLine("HelloWorld方法有{0}个参数:", helloWorldParamInfos.Length);  
  71.     foreach (ParameterInfo paramInfo in helloWorldParamInfos)  
  72.     {  
  73.         Console.WriteLine("参数名:{0},参数类型:{1}", paramInfo.Name, paramInfo.ParameterType.Name);  
  74.     }  
  75.   
  76.     //获取HelloWorld返回的数据类型  
  77.     string helloWorldReturnType = helloWorld.ReturnType.Name;  
  78.     Console.WriteLine("HelloWorld返回的数据类型是{0}", helloWorldReturnType);  
  79.       
  80.   
  81.       
  82.     Console.WriteLine("\n==============================================================");      
  83.     //调用Add方法  
  84.     MethodInfo add = t.GetMethod("Add");  
  85.     int a = 10, b = 20;//Add方法的参数  
  86.     object[] addParams = new object[]{a, b};  
  87.     object addReturn = add.Invoke(obj, addParams);  
  88.     Console.WriteLine("调用HelloWorld方法,{0} + {1} = {2}", a, b, addReturn.ToString());  
  89.   
  90.     //获取Add方法的参数  
  91.     ParameterInfo[] addParamInfos = add.GetParameters();  
  92.     Console.WriteLine("Add方法有{0}个参数:", addParamInfos.Length);  
  93.     foreach (ParameterInfo paramInfo in addParamInfos)  
  94.     {  
  95.         Console.WriteLine("参数名:{0},参数类型:{1}", paramInfo.Name, paramInfo.ParameterType.Name);  
  96.     }  
  97.   
  98.     //获取Add返回的数据类型  
  99.     string addReturnType = add.ReturnType.Name;  
  100.     Console.WriteLine("Add返回的数据类型:{0}", addReturnType);  
  101.   
  102.   
  103.       
  104.     Console.WriteLine("\n==============================================================");      
  105.     //调用GetDate方法  
  106.     MethodInfo getDate = t.GetMethod("GetDate");  
  107.     object getDateReturn = getDate.Invoke(obj, null);  
  108.     Console.WriteLine("调用GetDate方法,返回{0}", getDateReturn.ToString());  
  109.   
  110.     //获取GetDate方法的参数  
  111.     ParameterInfo[] getDateParamInfos = getDate.GetParameters();  
  112.     Console.WriteLine("GetDate方法有{0}个参数:", getDateParamInfos.Length);  
  113.     foreach (ParameterInfo paramInfo in getDateParamInfos)  
  114.     {  
  115.         Console.WriteLine("参数名:{0},参数类型:{1}", paramInfo.Name, paramInfo.ParameterType.Name);  
  116.     }  
  117.   
  118.     //获取Add返回的数据类型  
  119.     string getDateReturnType = getDate.ReturnType.Name;  
  120.     Console.WriteLine("GetDate返回的数据类型:{0}", getDateReturnType);  
  121.       
  122.   
  123.     Console.WriteLine("\n\n==============================================================");  
  124.     Console.WriteLine("服务信息");  
  125.     Console.WriteLine("服务名称:{0},服务描述:{1}", sd.Services[0].Name, sd.Services[0].Documentation);  
  126.     Console.WriteLine("服务提供{0}个方法:", sd.PortTypes[0].Operations.Count);  
  127.     foreach (Operation op in sd.PortTypes[0].Operations)  
  128.     {  
  129.         Console.WriteLine("方法名称:{0},方法描述:{1}", op.Name, op.Documentation);  
  130.     }              
  131.   
  132.     Console.ReadKey();  
  133. }  


  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值