博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WebService代理类——动态调用WebService
阅读量:5094 次
发布时间:2019-06-13

本文共 6775 字,大约阅读时间需要 22 分钟。

using System;

using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Collections;
using System.Web;

 

namespace Wicresoft.ITSG.Components.Utilities

{
    /// <summary>
    /// 调用WebService帮助类
    /// </summary>
    public class WebServiceHelper
    {
        /// <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)
        {
            return InvokeWebService(url, null, methodname, args);
        }

 

        #region 原方法

        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url">>WSDL服务地址</param>
        /// <param name="classname"></param>
        /// <param name="methodname">方法名</param>
        /// <param name="args">参数</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 = GetWsClassName(url);
            }
            WebClient wc = null;
            Stream stream = null;
            CSharpCodeProvider csc = null;
            try
            {
                //获取WSDL
                wc = new WebClient();
                stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

 

                //生成客户端代理类代码

                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

 

                //设定编译参数

                csc = 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 = csc.CompileAssemblyFromDom(cplist, ccu);
                if (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);
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
            finally  //最后要释放资源
            {
                if (stream != null)
                {
                    stream.Close();
                    //stream.Dispose();
                }
                if (wc != null)
                {
                    wc.Dispose();
                }
                if (csc != null)
                {
                    csc.Dispose();
                }
            }
        }
        #endregion

 

        private static string GetWsClassName(string wsUrl)

        {
            string className = null;
            if (!String.IsNullOrEmpty(wsUrl))
            {
                int startIndex = wsUrl.LastIndexOf('/') + 1;
                if (startIndex > 0)
                {
                    className = wsUrl.Substring(startIndex).Split('.')[0];
                }
            }
            return className;
        }

 

        #region sso专用方法
        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url"></param>
        /// <param name="classname"></param>
        /// <param name="methodname"></param>
        /// <param name="args"></param>
        /// <param name="dllCacheHours"></param>
        /// <returns></returns>
        public static object InvokeSSO_WebService(string url, string Dllname, string methodname, object[] args, int dllCacheHours)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
           
            string classname = GetWsClassName(url);

 

            System.Web.Caching.Cache myAssemblyCache = HttpContext.Current.Cache;

            //初始缓存信息
            if (myAssemblyCache["AssemblyCache"] == null)
            {
                myAssemblyCache.Insert("AssemblyCache", new Hashtable(), null, DateTime.Now.AddHours(dllCacheHours), TimeSpan.Zero);

 

                if (myAssemblyCache["AssemblyCache"] == null)

                {
                    //防配置失效
                    myAssemblyCache.Insert("AssemblyCache", new Hashtable(), null, DateTime.Now.AddHours(24), TimeSpan.Zero);
                }
            }

 

            //取得缓存

            Hashtable myHS = (Hashtable)myAssemblyCache["AssemblyCache"];

 

            WebClient wc = null;

            Stream stream = null;
            CSharpCodeProvider csc = null;
            ServiceDescription sd = null;
            ServiceDescriptionImporter sdi = null;
            CodeNamespace cn = null;
            CodeCompileUnit ccu = null;
            CompilerParameters cplist = null;
            CompilerResults cr = null;

 

            System.Reflection.Assembly assembly = null;

            System.Reflection.MethodInfo mi = null;

 

            try

            {
                //没缓存重新生成
                if (!myHS.ContainsKey(Dllname))
                {
                    //获取WSDL
                    wc = new WebClient();
                    stream = wc.OpenRead(url + "?WSDL");
                    sd = ServiceDescription.Read(stream);
                    sdi = new ServiceDescriptionImporter();
                    sdi.AddServiceDescription(sd, "", "");
                    cn = new CodeNamespace(@namespace);

 

                    //生成客户端代理类代码

                    ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);

 

                    //设定编译参数

                    csc = new CSharpCodeProvider();
                    cplist = new CompilerParameters();
                    cplist.GenerateExecutable = false;
                    cplist.GenerateInMemory = true;
                    //cplist.OutputAssembly = Dllname;

 

                    cplist.ReferencedAssemblies.Add("System.dll");

                    cplist.ReferencedAssemblies.Add("System.XML.dll");
                    cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                    cplist.ReferencedAssemblies.Add("System.Data.dll");

 

                    //编译代理类

                    cr = csc.CompileAssemblyFromDom(cplist, ccu);
                    if (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());
                    }

 

                    //生成代理实例,并调用方法

                    assembly = cr.CompiledAssembly;
                    //记录缓存
                    myHS.Add(Dllname, assembly);

 

                    Wicresoft.ITSG.Components.Utilities.LogUtility.CreateLogManager().Debug("DLL记缓存:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "*" + myHS.Count.ToString() + "*" + Dllname);

                }

 

                assembly = (System.Reflection.Assembly)myHS[Dllname];

                Wicresoft.ITSG.Components.Utilities.LogUtility.CreateLogManager().Debug("DLL取缓存:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "*" + Dllname);
                //assembly = System.Reflection.Assembly.LoadFrom(@"C:\inetpub\wwwroot\wss\VirtualDirectories\80\bin\" + Dllname);
                Type t = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                mi = t.GetMethod(methodname);
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    //stream.Dispose();
                }
                if (wc != null)
                {
                    wc.Dispose();
                }

 

                if (csc != null)

                {
                    csc.Dispose();
                }

 

                if (sd != null)

                {
                    sd = null;
                }

 

                if (sdi != null)

                {
                    sdi = null;
                }

 

                if (cn != null)

                {
                    cn = null;
                }

 

                ccu = null;
                cplist = null;
                cr = null;
                mi = null;
            }
        }
        #endregion
    }
}

 

转载于:https://www.cnblogs.com/xiaxianglanyu/p/3340418.html

你可能感兴趣的文章
生活大爆炸之何为光速
查看>>
[Typescript] Specify Exact Values with TypeScript’s Literal Types
查看>>
Illustrated C#学习笔记(一)
查看>>
理解oracle中连接和会话
查看>>
Scrapy实战篇(三)之爬取豆瓣电影短评
查看>>
HDU 5510 Bazinga KMP
查看>>
[13年迁移]Firefox下margin-top问题
查看>>
Zookeeper常用命令 (转)
查看>>
Enterprise Library - Data Access Application Block 6.0.1304
查看>>
重构代码 —— 函数即变量(Replace temp with Query)
查看>>
Bootstrap栅格学习
查看>>
程序员的数学
查看>>
聚合与组合
查看>>
洛谷 P2089 烤鸡【DFS递归/10重枚举】
查看>>
Linux基本操作
查看>>
osg ifc ifccolumn
查看>>
C++ STL partial_sort
查看>>
WebDriverExtensionsByC#
查看>>
我眼中的技术地图
查看>>
lc 145. Binary Tree Postorder Traversal
查看>>