1.动态调用WebService?
解决方案:添加动态调用WebService类WebServiceHelper;代码如下:
WebServiceHelper
using System;
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
}
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[](即实体集合等复杂对象),如何传入以及接收参数?
解决方案:第一步序列化对象
序列化对象
#region 序列化在内存中
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
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
代码
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);
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);
}
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);
}