C# 动态调用webservice

  最近项目中,用到动态调用webservice的内容,此处记录下来,留着以后COPY(我们只需要在XML,config文件,或者数据库中配置webservice连接地址和方法名即可使用);

  

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using Microsoft.CSharp;

namespace consoleTest
{
    public class DynWebServiceUtil
    {
         private const string WS_WSDL = "?WSDL";
        private const string WS_DLL_SYSTEM = "System.dll";
        private const string WS_DLL_XML = "System.XML.dll";
        private const string WS_DLL_WS = "System.Web.Services.dll";
        private const string WS_DLL_DATA = "System.Data.dll";
        private const string WS_NAMESPACE = "EnterpriseServerBase.WebService.DynamicWebCalling";

// 保存已编译生成的webservice代理
        private static IDictionary<string, HttpWebClientProtocol> mWebServiceList;

        /// <summary>
        /// 静态构造函数
        /// </summary>
        static DynWebServiceUtil()
        {
            mWebServiceList = new Dictionary<string, HttpWebClientProtocol>();
        }

        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="methodName">方法名</param>
        /// <param name="args">方法参数</param>
        /// <returns>方法返回值</returns>
        public static object InvokeWebService(string url, string methodName, object[] args)
        {
            string strProxyIp = ConfigurationManager.AppSettings["ProxyIp"];
            string strProxyPort = ConfigurationManager.AppSettings["ProxyPort"];
            WebProxy webProxy = string.IsNullOrEmpty(strProxyIp) || string.IsNullOrEmpty(strProxyPort)
                ? null : new WebProxy(strProxyIp, int.Parse(strProxyPort));
            return InvokeWebService(url, methodName, args, webProxy);
        }

        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="methodName">方法名</param>
        /// <param name="args">方法参数</param>
        /// <param name="webProxy">外网代理服务器</param>
        /// <returns>方法返回值</returns>
        public static object InvokeWebService(string url, string methodName, object[] args, WebProxy webProxy)
        {
            return InvokeWebService(url, null, methodName, args, webProxy);
        }

        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="className">类名</param>
        /// <param name="methodName">方法名</param>
        /// <param name="args">方法参数</param>
        /// <param name="webProxy">外网代理服务器</param>
        /// <returns>方法返回值</returns>
        public static object InvokeWebService(string url,
            string className, string methodName, object[] args, WebProxy webProxy)
        {
            ServicePointManager.Expect100Continue = false;
            HttpWebClientProtocol wsProxy = GetWebService(url, className, webProxy);
            MethodInfo mi = wsProxy.GetType().GetMethod(methodName);

            try
            {
                return mi.Invoke(wsProxy, args);
            }
            catch (TargetInvocationException exTI)
            {
                throw new DynWebServiceMethodInvocationException(
                    exTI.InnerException.Message,
                    new Exception(exTI.InnerException.StackTrace));
            }
        }

        /// <summary>
        /// 取得类名
        /// </summary>
        /// <param name="wsUrl">地址</param>
        /// <returns>类名</returns>
        private static string GetWsClassName(string wsUrl)
        {
            string[] parts = wsUrl.Split('/');
            string[] pps = parts[parts.Length - 1].Split('.');

            return pps[0];
        }

        /// <summary>
        /// 取得webservice代理类
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="className">类名</param>
        /// <param name="webProxy">外网代理服务器</param>
        /// <returns>webservice代理类</returns>
        private static HttpWebClientProtocol GetWebService(string url, string className, WebProxy webProxy)
        {
            string strUrl = url.ToLower();
            HttpWebClientProtocol wsProxy = null;
            if (mWebServiceList.ContainsKey(strUrl))
            {
                wsProxy = mWebServiceList[strUrl];
            }
            else
            {
                if (string.IsNullOrEmpty(className))
                {
                    className = GetWsClassName(url);
                }

                // 获取WSDL
                WebClient wc = new WebClient();

                // 访问url是否需要通过代理服务器
                if (webProxy != null)
                {
                    wc.Proxy = webProxy;
                }

                Stream stream = wc.OpenRead(url + WS_WSDL);
                ServiceDescription sd = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, null, null);

                // 生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                CodeNamespace cn = new CodeNamespace(WS_NAMESPACE);
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                // 设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add(WS_DLL_SYSTEM);
                cplist.ReferencedAssemblies.Add(WS_DLL_XML);
                cplist.ReferencedAssemblies.Add(WS_DLL_WS);
                cplist.ReferencedAssemblies.Add(WS_DLL_DATA);

                // 编译代理类
                CSharpCodeProvider csc = new CSharpCodeProvider();
                CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (cr.Errors.HasErrors)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(Environment.NewLine);
                    }

                    throw new DynWebServiceCompileException(sb.ToString());
                } // end of if (cr.Errors.HasErrors)

                // 生成代理实例
                Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(WS_NAMESPACE + "." + className, true, true);
                wsProxy = (HttpWebClientProtocol)Activator.CreateInstance(t);
                mWebServiceList[strUrl] = wsProxy;
            } // enf of if (mWebServiceList.ContainsKey(strUrl))

            // 访问url是否需要通过代理服务器
            if (webProxy != null)
            {
                wsProxy.Proxy = webProxy;
            }

            return wsProxy;
        }


    }
}


调用:
DynWebServiceUtil.InvokeWebService(
                    string.Format("{0}", tbWebService.Rows[0]["SERVICE_URL"]),
                    string.Format("{0}", tbWebService.Rows[0]["SERVICE_METHOD_NAME"]),
                    new object[] { "asnno"})

 

posted on 2016-06-13 17:16  大雄的脚印  阅读(410)  评论(0编辑  收藏  举报