核心類庫:使用C#編譯輔助類CodeNamespace,CSharpCodeProvider,CompilerParameters,CompilerResultsweb
經過反射建立代理實例並調用方法app
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;ide
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);ui
//添加超時時間
if (!string.IsNullOrEmpty(timeOut))
{
int timeout = 0;
int.TryParse(timeOut, out timeout);url
if (timeout == 0)
timeout = 1200;spa
//設置超時時間
((System.Web.Services.Protocols.WebClientProtocol)(obj)).Timeout = timeout * 1000;//毫秒s,timeOut超時時間設置爲分鐘
}.net
return mi.Invoke(obj, args);代理
}
}excel
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; } } }