溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

C#中怎么動(dòng)態(tài)調(diào)用Web服務(wù)

發(fā)布時(shí)間:2021-06-24 16:27:33 來(lái)源:億速云 閱讀:148 作者:Leah 欄目:編程語(yǔ)言

本篇文章給大家分享的是有關(guān)C#中怎么動(dòng)態(tài)調(diào)用Web服務(wù),小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。

(1)首先在Web引用中的本地代理類(lèi)中添加一個(gè)構(gòu)造函數(shù),這個(gè)構(gòu)造函數(shù)是以Web Service的URL為參數(shù)的重載方法。

復(fù)制  保存

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           '添加一個(gè)帶參數(shù)的構(gòu)造函數(shù)。          Public Sub New(ByVal strUrl As String)               MyBase.New()               Me.Url = strUrl           End Sub

(2)將Web Service的url配置在調(diào)用Web Service的應(yīng)用程序的配置文件中。(其中的value可以隨時(shí)修改。)

復(fù)制  保存

< 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)調(diào)用時(shí),根據(jù)配置文件的Url動(dòng)態(tài)的生成Web Service。

復(fù)制  保存       

'要調(diào)用的Web Service的URL          Dim strWebSvsUrl As String          '聲明一個(gè)要調(diào)用的Web Service          Dim objSVSGC As WebSvs_GC. SVSGC          '調(diào)用Web Service的遠(yuǎn)程方法的返回值          Dim strReturnValue As String          Try              '從配置文件中取得Web Service的URL              strWebSvsUrl = _               System.Configuration.ConfigurationSettings.AppSettings("SVSGC_URL")               '生成一個(gè)Web Service實(shí)例              objSVSGC = New WebSvs_GC.SVSGC (strWebSvsUrl)              '調(diào)用這個(gè)Web Service里的遠(yuǎn)程方法              strReturnValue = objSVSGC.HelloWorld()          Catch ex As Exception          End Try

C#動(dòng)態(tài)調(diào)用Web服務(wù)方法二:完全動(dòng)態(tài)處理,傳入服務(wù)服務(wù)網(wǎng)址,方法名和參數(shù)即可.

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   {       /* 調(diào)用方式        *   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>           /// 動(dòng)態(tài)調(diào)用web服務(wù)           /// < /summary>           /// < param name="url">WSDL服務(wù)地址< /param>           /// < param name="methodname">方法名< /param>           /// < param name="args">參數(shù)< /param>           /// < returns>< /returns>           public static object InvokeWebService(string url, string methodname, object[] args)           {               return WebServiceHelper.InvokeWebService(url, null, methodname, args);           }            /// < summary>           /// 動(dòng)態(tài)調(diào)用web服務(wù)           /// < /summary>           /// < param name="url">WSDL服務(wù)地址< /param>           /// < param name="classname">類(lèi)名< /param>           /// < param name="methodname">方法名< /param>           /// < param name="args">參數(shù)< /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);                    //生成客戶(hù)端代理類(lèi)代碼                   CodeCompileUnit ccu = new CodeCompileUnit();                   ccu.Namespaces.Add(cn);                   sdi.Import(cn, ccu);                   CSharpCodeProvider icc = new CSharpCodeProvider();                    //設(shè)定編譯參數(shù)                   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");                    //編譯代理類(lèi)                   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());                   }                    //生成代理實(shí)例,并調(diào)用方法                   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       }   }

返回時(shí)如果不是字符串,即強(qiáng)制轉(zhuǎn)換,如返回是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#動(dòng)態(tài)調(diào)用Web服務(wù)方法三:URL Behavior 屬性

如果知道服務(wù)的方法和參數(shù),只是調(diào)用的URL網(wǎng)址會(huì)隨時(shí)變化,那么可以手工創(chuàng)建一個(gè)服務(wù),添加上對(duì)應(yīng)的的方法和傳入?yún)?shù),然后引入到項(xiàng)目中,就可以直接開(kāi)發(fā),在創(chuàng)建服務(wù)的實(shí)例化時(shí),才修改對(duì)應(yīng)的URL即可.

例如服務(wù)中有個(gè)方法叫GetTax,那么就可以這樣改:

GetTax.GetTax GetTax1 = new GetTax.GetTax();   GetTax1.Url = "http://" + WebIp1 + "/pub_wa_gspsp1/gettax.asmx";        //動(dòng)態(tài)引入服務(wù)器                      DataSet DS1 = GetTax1.GetTaxMx(Bm1, OldBz, Fpl, SLx, StaDa, EndDa);   //調(diào)用服務(wù)器返回開(kāi)票數(shù)據(jù)

以上就是C#中怎么動(dòng)態(tài)調(diào)用Web服務(wù),小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI