• WebService代理类——动态调用WebService


    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:inetpubwwwrootwssVirtualDirectories80in" + 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
        }
    }

  • 相关阅读:
    Day 9
    Day 8
    Day 7
    Day 6
    Day 5
    Day 4
    Day 3
    Day 2
    Day 1
    解决vue-cli3不停请求 /sockjs-node/info?t= 问题
  • 原文地址:https://www.cnblogs.com/xiaxianglanyu/p/3340418.html
Copyright © 2020-2023  润新知