C # How to dynamically call Web Services

Source: Internet
Author: User

When developing C # WinForm, we sometimes call the Web service, which is a local service, you can directly create a Web service object to reference in the Code by introducing Web References in the Project. In fact, the principle is that C # helps you automatically create a client proxy class to call WebService, however, if the called service is dynamic, for example, if several IIS services have the same service, enter a specific IP Address at runtime to determine which service to call. How can this problem be achieved.

Method 1: manually add a Web reference and modify the local proxy class. Finally, the Web Service URI is deployed in the configuration file. The procedure is as follows:

The following code shows how to configure a dynamic Web Service. Take Service Unit C (Class Name: Web_SVSGC) as an example:

(1) first, add a constructor to the local proxy class in the Web reference. This constructor is an overload method with the URL of the Web Service as the parameter.
Copy and save Namespace Web_SVSGC
'<Remarks/>
<System. diagnostics. debuggerStepThroughAttribute (), _ System. componentModel. designerCategoryAttribute ("code"), _ System. web. services. webServiceBindingAttribute (Name: = "sv1_soap", [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

'Add a constructor with parameters.
Public Sub New (ByVal strUrl As String)
MyBase. New ()
Me. Url = strUrl
End Sub

(2) configure the url of the Web Service in the configuration file of the application that calls the Web Service. (The value can be modified at any time .)

Copy and save <configuration>
<Deleetask>
<Add key = "SVSGA_URL" value = "http: // 192.168.108.188/QDN/SERVICE/SVSGA. asmx" QDN/SERVICE/SVSGA. asmx "/>
</AppSettings>
</Configuration> <configuration>
<Deleetask>
<Add key = "SVSGA_URL" value = "http: // 192.168.108.188/QDN/SERVICE/SVSGA. asmx" QDN/SERVICE/SVSGA. asmx "/>
</AppSettings>
</Configuration>

(3) the Web Service is dynamically generated based on the Url of the configuration file during the call.
Copy and save the 'url of the Web Service to be called
Dim strWebSvsUrl As String
'Declare a Web Service to be called
Dim objSVSGC As WebSvs_GC. SVSGC
'Return value of the remote method for calling Web Service
Dim strReturnValue As String
Try
'Retrieve the Web Service URL from the configuration file
StrWebSvsUrl = _
System. Configuration. ConfigurationSettings. receivettings ("SVSGC_URL ")
'Generate a Web Service instance
ObjSVSGC = New WebSvs_GC.SVSGC (strWebSvsUrl)
'Call the remote method in this Web Service
StrReturnValue = objSVSGC. HelloWorld ()
Catch ex As Exception
End Try

Method 2: Completely dynamic processing. Just enter the service URL, method name, and parameter.

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
{
/* Call Method
* 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>
/// Dynamically call the web Service
/// </Summary>
/// <Param name = "url"> WSDL service address </param>
/// <Param name = "methodname"> method name </param>
/// <Param name = "args"> parameter </param>
/// <Returns> </returns>
Public static object InvokeWebService (string url, string methodname, object [] args)
{
Return WebServiceHelper. InvokeWebService (url, null, methodname, args );
}

/// <Summary>
/// Dynamically call the web Service
/// </Summary>
/// <Param name = "url"> WSDL service address </param>
/// <Param name = "classname"> class name </param>
/// <Param name = "methodname"> method name </param>
/// <Param name = "args"> parameter </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
{
// Obtain the 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 );

// Generate client proxy code
CodeCompileUnit ccu = new CodeCompileUnit ();
Ccu. Namespaces. Add (cn );
Sdi. Import (cn, ccu );
CSharpCodeProvider icc = new CSharpCodeProvider ();

// Set compilation Parameters
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 ");

// Compile the proxy class
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 ());
}

// Generate a proxy instance and call the Method
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
}
}
If the returned result is not a string, that is, forced conversion. If the returned result is 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;

Method 3: URL Behavior attributes

If you know the service method and parameters, but the called URL changes at any time, you can manually create a service, add the corresponding method and input parameters, and then introduce them to the project, you can directly develop the service and modify the corresponding URL only when you create the service instantiation.

For example, if the service has a method called GetTax, you can change it as follows:

GetTax. GetTax GetTax1 = new GetTax. GetTax ();
GetTax1.Url = "http: //" + WebIp1 + "/pub_wa_gspsp1/gettax. asmx"; // dynamically introduce the server

DataSet DS1 = GetTax1.GetTaxMx (Bm1, OldBz, Fpl, SLx, StaDa, EndDa); // call the server to return the invoicing data

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/turejackon/archive/2008/12/30/3658236.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.