WebService 동적 호출 및 복잡한 객체 전달

6763 단어 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[](즉, 실체 집합과 같은 복잡한 대상)인데 어떻게 들어오고 받습니까?
해결 방안: 1단계 서열화 대상
 
        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

 
2단계: 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);

 
3단계: 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);

}

 

좋은 웹페이지 즐겨찾기