• 动态调用WebService以及传递复杂对象


    1.动态调用WebService?
    解决方案:添加动态调用WebService类WebServiceHelper;代码如下:

    using System.Collections.Generic;
    
    using System.Web;
    
    using System.Net;
    
    using System.Web.Services.Description;
    
    using System.Text;
    
    using System.IO;
    
    using System.CodeDom;
    
    using Microsoft.CSharp;
    
    using System.CodeDom.Compiler;
    
    /// <summary>
    
    ///WebServiceHelper 的摘要说明
    
    /// </summary>
    
    public class WebServiceHelper
    
    {
    
         public WebServiceHelper()
    
         {
    
             //
    
             //TODO: 在此处添加构造函数逻辑
    
             //
    
         }
    
        #region InvokeWebService
    
        //动态调用web服务
    
        public static object InvokeWebService(string url, string methodname, object[] args)
    
        {
    
            return WebServiceHelper.InvokeWebService(url, null, methodname, args);
    
        }
    
     
    
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
    
        {
    
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
    
            if ((classname == null) || (classname == ""))
    
            {
    
                classname = WebServiceHelper.GetWsClassName(url);
    
            }
    
     
    
            try
    
            {
    
                //获取WSDL
    
                WebClient wc = new WebClient();
    
                Stream 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);
    
                CSharpCodeProvider csc = new CSharpCodeProvider();
    
                ICodeCompiler icc = csc.CreateCompiler();
    
     
    
                //设定编译参数
    
                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);
    
     
    
                return mi.Invoke(obj, args);
    
            }
    
            catch (Exception ex)
    
            {
    
                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];
    
        }
    
        #endregion
    
    }
    

     

    2.调用WebService时,传入参数为Entity[](即实体集合等复杂对象),如何传入以及接收参数?

    解决方案:第一步序列化对象

     

            XmlSerializer xs = new XmlSerializer(typeof(Entity[]));
    
            MemoryStream mstream = new MemoryStream();
    
            XmlTextWriter writer = new XmlTextWriter(mstream, Encoding.Default);
    
            xs.Serialize(mstream, en);
    
            writer.Close();
    
            string str = Encoding.UTF8.GetString(mstream.ToArray());
    
            #endregion
    
            #region 写入文件再读取出字符串
    
            //FileStream fs = new FileStream("c:\\aaa.txt", FileMode.OpenOrCreate);
    
            //xs = new XmlSerializer(typeof(Entity[]));
    
            //xs.Serialize(fs, en);
    
            //fs.Close();
    
     
    
            //fs = new FileStream("c:\\aaa.txt", FileMode.Open, FileAccess.Read);
    
            //StreamReader reader = new StreamReader(fs, Encoding.Default);
    
            //str = reader.ReadToEnd();
    
            //reader.Close();
    
            //reader.Dispose();
    
            //fs.Close();
    
            //fs.Dispose();
    
            #endregion
    

    第二步:动态调用WebService

     

    代码 
    
    
    Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
    string url = "http://localhost:4494/SMWebService/WebService_S.asmx";
    
            object[] args = new object[2];
    
            args[0] = mapname;
    
            args[1] = str;
    
            object result = WebServiceHelper.InvokeWebService(url, "AddEntity", args);
    

    第三步:WebService中的处理过程(反序列化)

     

     [WebMethod]
    
        public bool AddEntity(string mapname,string strentites)
    
        {
    
    Stream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(strentites));
    
             XmlSerializer xml = new XmlSerializer(typeof(Entity[]));
    
                Entity[] entities = (Entity[])xml.Deserialize(stream);
    
    }
    
  • 相关阅读:
    [Outlook] Outlook2013能收但无法发送邮件-0x800CCC13, 0x800CCC0B, 0x8004210B
    [Mobile] 手机浏览器输入框-数字输入框
    [Qcon] 百姓网开发总结
    [QCon] Scrum阅读随想
    [Spring] 事务级别定义
    [Monitor] 监控规则定义
    [Spring Batch] 图解Spring Batch原理
    [JavaCore] 微信手机浏览器版本判断
    Python 编码简单说
    矩阵或多维数组两种常用实现方法
  • 原文地址:https://www.cnblogs.com/amylis_chen/p/2816534.html
Copyright © 2020-2023  润新知