核心类库:使用C#编译辅助类CodeNamespace,CSharpCodeProvider,CompilerParameters,CompilerResults
通过反射创建代理实例并调用方法
using Microsoft.CSharp;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Services.Description;
namespace Common
{
public class WSHelper
{
/// < summary>
/// 动态调用web服务
/// < /summary>
/// < param name="url">WSDL服务地址< /param>
/// <param name="strNamespace">命名空间,与WebServiceG一致</param>
/// < param name="methodname">方法名< /param>
/// < param name="args">参数< /param>
/// < returns>< /returns>
public static object InvokeWebService(string url, string strNamespace, string methodname, object[] args, string timeOut = "")
{
return WSHelper.InvokeWebService(url, strNamespace, "", methodname, args, timeOut);
}
/// < summary>
/// 动态调用web服务
/// < /summary>
/// < param name="url">WSDL服务地址< /param>
/// < param name="classname">类名< /param>
/// < param name="methodname">方法名< /param>
/// < param name="args">参数< /param>
/// < param name="timeOut">webservice的超时时间(分钟)</param>
/// < returns>< /returns>
public static object InvokeWebService(string url, string @namespace, string classname, string methodname, object[] args,string timeOut = "")
{
if ((classname == null) || (classname == ""))
{
classname = WSHelper.GetWsClassName(url);
}
try
{ //获取WSDL
//WebClient wc = new WebClient();
url = url + "?WSDL";
//Stream stream = wc.OpenRead(url + "?WSDL");
// 创建 HttpWebRequest 实例
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
// 设置跟随重定向
Request.AllowAutoRedirect = true;
Regex __RegexUri_ = new Regex("^https://", RegexOptions.IgnoreCase);
if (__RegexUri_.IsMatch(url))
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
Request.Timeout = 1200000;
Request.Method = "GET";
Request.Accept = "image/gif, image/x-xbitmap,image/jpeg, image/pjpeg,application/x-shockwave-flash,application/vnd.ms-excel, application/vnd.ms-powerpoint,application/msword, */*";
Request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322); Http STdns";
Request.CookieContainer = new CookieContainer();
Request.Referer = "";
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
// 获取状态值
HttpStatusCode __StatusCode__ = Response.StatusCode;
if (__StatusCode__ == HttpStatusCode.OK)
{
using (Stream reader = Response.GetResponseStream())
{
ServiceDescription sd = ServiceDescription.Read(reader);
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);
//添加超时时间
if (!string.IsNullOrEmpty(timeOut))
{
int timeout = 0;
int.TryParse(timeOut, out timeout);
if (timeout == 0)
timeout = 1200;
//设置超时时间
((System.Web.Services.Protocols.WebClientProtocol)(obj)).Timeout = timeout * 1000;//毫秒s,timeOut超时时间设置为分钟
}
return mi.Invoke(obj, args);
}
}
return null;
}
catch (Exception ex)
{
return null;
//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];
}
}
/// <summary>
/// 当 Uri 资源为 HTTPS 时,忽略证书。
/// </summary>
public class TrustAllCertificatePolicy : ICertificatePolicy
{
public TrustAllCertificatePolicy()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public bool CheckValidationResult(ServicePoint _ServicePoint_, X509Certificate _Cert_, WebRequest _WebRequest_, int _Problem_)
{
return true;
}
}
}