C#动态调用WebService方法
1. WebService中的方法
/// <summary>
/// WebServiceDemo 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class WebServiceDemo : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld(string name)
{
return "Hello World,"+name;
}
}
2. C#动态调用
1) 动态调用WebService的方法
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Services.Description;
using System.CodeDom;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
namespace Tools
{
public delegate object InvokeWebServiceHandler(string serviceUrl, string classname, string methodname, object[] objects);
public class WebServiceHelper
{
/// <summary>
/// 动态调用WebService
/// </summary>
/// <param name="url">WebService地址</param>
/// <param name="classname">WebService类名</param>
/// <param name="methodname">调用的类名</param>
/// <param name="args">参数数组</param>
public object InvokeWebService(string url, string classname, string methodname, object[] args)
{
try
{
string @namespace = "fangqm.Netbank.WebService.webservice";
if (classname == null || classname == "")
{
classname = GetClassName(url);
}
SetCertificatePolicy();
//获取服务描述语言(WSDL)
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url + "?WSDL");//【1】
ServiceDescription sd = ServiceDescription.Read(stream);//【2】
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();//【3】
sdi.AddServiceDescription(sd, "", "");
CodeNamespace cn = new CodeNamespace(@namespace);//【4】
//生成客户端代理类代码
CodeCompileUnit ccu = new CodeCompileUnit();//【5】
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
CSharpCodeProvider csc = new CSharpCodeProvider();//【6】
ICodeCompiler icc = csc.CreateCompiler();//【7】
//设定编译器的参数
CompilerParameters cplist = new CompilerParameters();//【8】
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);//【9】
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new StringBuilder();
foreach (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 bj = Activator.CreateInstance(t);//【10】
System.Reflection.MethodInfo mi = t.GetMethod(methodname);//【11】
return mi.Invoke(bj, args);
}
catch (Exception ex)
{
return null;
}
}
private string GetClassName(string url)
{
//假如URL为"http://localhost:51837/Service1.asmx"
//最终的返回值为 Service1
string[] parts = url.Split('/');
string[] pps = parts[parts.Length - 1].Split('.');
return pps[0];
}
/// <summary>
/// Sets the cert policy.
/// </summary>
public static void SetCertificatePolicy()
{
ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
}
/// <summary>
/// Remotes the certificate validate.
/// </summary>
private static bool RemoteCertificateValidate(
object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error)
{
// trust any certificate!!!
System.Console.WriteLine("Warning, trust any certificate");
return true;
}
/// <summary>
///CallBack method of dynamic Invoke WebService
/// </summary>
/// <param name="ar">status of Async operate</param>
public void CallBackForWebservice(IAsyncResult iar)
{
InvokeWebServiceHandler dn = (InvokeWebServiceHandler)iar.AsyncState;
if (iar.IsCompleted == true)
{
try
{
dn.EndInvoke(iar);
}
catch (Exception e)
{
}
}
}
}
}
2) 同步调用
string strWebServiceUrl="http://localhost:10974/WebServiceDemo.asmx";
object[] objects = new object[] {“500”};
return InvokeWebService(serviceUrl, "", "HelloWorld", objects);
3) 异步调用
WebServiceHelper wbHelper = new WebServiceHelper();
InvokeWebServiceHandler webServiceHandler = new InvokeWebServiceHandler(wbHelper.InvokeWebService);//创建委托实例
string strWebServiceUrl="http://localhost:10974/WebServiceDemo.asmx";
object[] objects = new object[] { "king"};// 准备参数
webServiceHandler.BeginInvoke(strWebServiceUrl, "", "HelloWorld", objects,new AsyncCallback(CallBackMethod), webServiceHandler);//异步委托调用
// 请求WebService完成后,回调的方法
privatevoid CallBackMethod(IAsyncResult ar)
{
if (ar.IsCompleted == true)
{
string strData = dele.EndInvoke(ar).ToString();//获取方法返回值
}
}