温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#中怎么动态调用Web服务

发布时间:2021-06-24 16:27:33 来源:亿速云 阅读:147 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关C#中怎么动态调用Web服务,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

(1)首先在Web引用中的本地代理类中添加一个构造函数,这个构造函数是以Web Service的URL为参数的重载方法。

复制  保存

Namespace Web_SVSGC      '< remarks/>     < System.Diagnostics.DebuggerStepThroughAttribute(),  _     System.ComponentModel.DesignerCategoryAttribute("code"),  _     System.Web.Services.WebServiceBindingAttribute(Name:="SVSGCSoap", [Namespace]:="http://tempuri.org/QYJSERVICE/SVSGC"),  _     System.Xml.Serialization.XmlIncludeAttribute(GetType(Attribute))>  _      Public Class SVSGC          Inherits System.Web.Services.Protocols.SoapHttpClientProtocol      '< remarks/>         Public Sub New()              MyBase.New              Me.Url = "http://localhost/QYJSERVICE/WEBSERVICE/SERVICE/SVSGC.asmx"         End Sub           '添加一个带参数的构造函数。          Public Sub New(ByVal strUrl As String)               MyBase.New()               Me.Url = strUrl           End Sub

(2)将Web Service的url配置在调用Web Service的应用程序的配置文件中。(其中的value可以随时修改。)

复制  保存

< configuration>     < appSettings>               < add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" />     < /appSettings> < /configuration>< configuration>     < appSettings>               < add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" />     < /appSettings> < /configuration>

(3)调用时,根据配置文件的Url动态的生成Web Service。

复制  保存       

'要调用的Web Service的URL          Dim strWebSvsUrl As String          '声明一个要调用的Web Service          Dim objSVSGC As WebSvs_GC. SVSGC          '调用Web Service的远程方法的返回值          Dim strReturnValue As String          Try              '从配置文件中取得Web Service的URL              strWebSvsUrl = _               System.Configuration.ConfigurationSettings.AppSettings("SVSGC_URL")               '生成一个Web Service实例              objSVSGC = New WebSvs_GC.SVSGC (strWebSvsUrl)              '调用这个Web Service里的远程方法              strReturnValue = objSVSGC.HelloWorld()          Catch ex As Exception          End Try

C#动态调用Web服务方法二:完全动态处理,传入服务服务网址,方法名和参数即可.

using System;   using System.Net;   using System.IO;   using System.CodeDom;   using Microsoft.CSharp;   using System.CodeDom.Compiler;   using System.Web.Services.Description;   using System.Web.Services.Protocols;    namespace HB.Common   {       /* 调用方式        *   string url = "http://www.webservicex.net/globalweather.asmx" ;        *   string[] args = new string[2] ;        *   args[0] = "Hangzhou";        *   args[1] = "China" ;        *   object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;        *   Response.Write(result.ToString());        */       public class WebServiceHelper       {           #region InvokeWebService           /// < summary>           /// 动态调用web服务           /// < /summary>           /// < param name="url">WSDL服务地址< /param>           /// < param name="methodname">方法名< /param>           /// < param name="args">参数< /param>           /// < returns>< /returns>           public static object InvokeWebService(string url, string methodname, object[] args)           {               return WebServiceHelper.InvokeWebService(url, null, methodname, args);           }            /// < summary>           /// 动态调用web服务           /// < /summary>           /// < param name="url">WSDL服务地址< /param>           /// < param name="classname">类名< /param>           /// < param name="methodname">方法名< /param>           /// < param name="args">参数< /param>           /// < returns>< /returns>           public static object InvokeWebService(string url, string classname, string methodname, object[] args)           {               string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";               if ((classname == null) || (classname == ""))               {                   classname = WebServiceHelper.GetWsClassName(url);               }                try               {                   //获取WSDL                   WebClient wc = new WebClient();                   Stream stream = wc.OpenRead(url + "?WSDL");                   ServiceDescription sd = ServiceDescription.Read(stream);                   ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();                   sdi.AddServiceDescription(sd, "", "");                   CodeNamespace cn = new CodeNamespace(@namespace);                    //生成客户端代理类代码                   CodeCompileUnit ccu = new CodeCompileUnit();                   ccu.Namespaces.Add(cn);                   sdi.Import(cn, ccu);                   CSharpCodeProvider icc = 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 = icc.CompileAssemblyFromDom(cplist, ccu);                   if (true == cr.Errors.HasErrors)                   {                       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());                   }                    //生成代理实例,并调用方法                   System.Reflection.Assembly assembly = cr.CompiledAssembly;                   Type t = assembly.GetType(@namespace + "." + classname, true, true);                   object obj = Activator.CreateInstance(t);                   System.Reflection.MethodInfo mi = t.GetMethod(methodname);                    return mi.Invoke(obj, args);                    /*                   PropertyInfo propertyInfo = type.GetProperty(propertyname);                   return propertyInfo.GetValue(obj, null);                   */               }               catch (Exception ex)               {                   throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));               }           }            private static string GetWsClassName(string wsUrl)           {               string[] parts = wsUrl.Split('/');               string[] pps = parts[parts.Length - 1].Split('.');                return pps[0];           }           #endregion       }   }

返回时如果不是字符串,即强制转换,如返回是DataSet,则

string url = "http://www.webservicex.net/globalweather.asmx" ;   string[] args = new string[2] ;   args[0] = "Hangzhou";   args[1] = "China" ;   object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;   DataSet DSRe=(DataSet)result;

C#动态调用Web服务方法三:URL Behavior 属性

如果知道服务的方法和参数,只是调用的URL网址会随时变化,那么可以手工创建一个服务,添加上对应的的方法和传入参数,然后引入到项目中,就可以直接开发,在创建服务的实例化时,才修改对应的URL即可.

例如服务中有个方法叫GetTax,那么就可以这样改:

GetTax.GetTax GetTax1 = new GetTax.GetTax();   GetTax1.Url = "http://" + WebIp1 + "/pub_wa_gspsp1/gettax.asmx";        //动态引入服务器                      DataSet DS1 = GetTax1.GetTaxMx(Bm1, OldBz, Fpl, SLx, StaDa, EndDa);   //调用服务器返回开票数据

以上就是C#中怎么动态调用Web服务,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI