动态调用web服务

zdm0923 2006-11-02 02:36:23
我网上找了个动态动用的例子
using System;

using System.IO;

using System.Configuration;

using System.CodeDom;

using System.CodeDom.Compiler;

using System.Net;

using System.Web.Services;

using System.Web.Services.Description;

using Microsoft.CSharp;

using System.Collections;

using System.Reflection;



namespace WuYou.NetSignUp

{

/// <summary>

/// WebServiceHelper 的摘要说明。

/// </summary>

public class WebServiceHelper

{

private string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling" ; //命名空间

private Assembly assembly = null; //程序集;

private string classname = string.Empty; //类名称;

private Type t; //表示类型;

private object obj = null; //表示实例;

private Boolean isSuccess = false; //是否创建实例成功;





public WebServiceHelper(string Url,string classname)

{

if(classname == null || classname == string.Empty)

this.classname = GetWsClassName(Url);

else

this.classname = classname;



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);

stream.Close();



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

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());

}



assembly = cr.CompiledAssembly;

}

catch (System.Exception ex)

{

throw new Exception(ex.InnerException.Message,new Exception(ex.InnerException.StackTrace));

}

}



private Boolean CreateInstance()

{

try

{

t = assembly.GetType(@namespace+"."+classname,true,true);

obj = Activator.CreateInstance(t);

isSuccess = true;

}

catch (System.Exception e)

{

throw new Exception(e.Message);

}

return isSuccess;

}



public object InvokeWebService(string methodanme,object[] parms)

{



if(!isSuccess)

{

CreateInstance();

}



try

{

System.Reflection.MethodInfo mi = t.GetMethod(methodanme);



return mi.Invoke(obj,parms);



}

catch (System.Exception ex)

{

throw new Exception(ex.InnerException.Message,new Exception(ex.InnerException.StackTrace));

}



}



private string GetWsClassName(string wsUrl)

{

string[] parts = wsUrl.Split('/') ;

string[] pps = parts[parts.Length-1].Split('.') ;



return pps[0] ;

}

}

}

然后调用本地的
string url = "http://localhost/DymaticText/Service1.asmx" ;
string[] args=new string[2];
args[0] ="strere";
args[1] = "China" ;
object result = Proxy.InvokeWebService(url ,"HelloWorld " ,args) ;
this.label3.Text = result.ToString() ;
就出现错误"未将对象引用设置到对象的实例"
用网上别人提供的例子就可以测试成功
这是为什么?
谁碰到过这个问题并且解决了的告诉我一下啊
...全文
274 1 打赏 收藏 举报
写回复
1 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
scow 2006-11-02
  • 打赏
  • 举报
回复
我也写了一个,可以调用, 没发现问题, 如下:
const string DefaultUrl = "http://192.168.60.27/ServiceDS/Service.asmx?wsdl";
static Program instance = new Program();

static void Main(string[] args)
{
instance.InvokeMethod();
Console.ReadLine();
}

void InvokeMethod()
{
Assembly proxyAssembly = CreateWSProxy(DefaultUrl);
Type proxyType = proxyAssembly.GetType("WebServiceProxy.Service");
MethodInfo mi = proxyType.GetMethod("xxxMethod");
PropertyInfo pi = proxyType.GetProperty("Credentials");
object proxy = Activator.CreateInstance(proxyType);
pi.SetValue(proxy, CredentialCache.DefaultCredentials, new object[0]);
Console.WriteLine(mi.Invoke(proxy, new object[] { "xxx" }).ToString());
}

Assembly CreateWSProxy(string url)
{
if (String.IsNullOrEmpty(url))
return null;

ServiceDescription wsdl = GetWsdl(url);
CodeNamespace cns = new CodeNamespace("WebServiceProxy");
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(wsdl, null, null);
sdi.ProtocolName = "Soap";
sdi.Import(cns, null);

CSharpCodeProvider cp = new CSharpCodeProvider();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
cp.GenerateCodeFromNamespace(cns, sw, null);
string src = sb.ToString();
sw.Close();
Console.WriteLine(src);

CompilerParameters cmp = new CompilerParameters();
cmp.ReferencedAssemblies.Add("System.dll");
cmp.ReferencedAssemblies.Add("System.Xml.dll");
cmp.ReferencedAssemblies.Add("System.Web.Services.dll");
cmp.GenerateExecutable = false;
cmp.GenerateInMemory = true;
cmp.IncludeDebugInformation = false;

CompilerResults cr = cp.CompileAssemblyFromSource(cmp, src);

if (cr.Errors.Count > 0)
throw new Exception(string.Format("Build failed: {0} errors",
cr.Errors.Count));
return cr.CompiledAssembly;
}

ServiceDescription GetWsdl(string url)
{
WebRequest wreq = WebRequest.Create(url);
wreq.Credentials = CredentialCache.DefaultCredentials;
WebResponse resp = wreq.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
string desc = sr.ReadToEnd();
XmlTextReader xtr = new XmlTextReader(new StringReader(desc));

ServiceDescription wsdl = ServiceDescription.Read(xtr);
xtr.Close();
sr.Close();
stream.Close();
resp.Close();
return wsdl;
}
发帖
.NET社区

6.1w+

社区成员

.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
帖子事件
创建了帖子
2006-11-02 02:36
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。