日期:2014-05-19  浏览次数:20972 次

关于调用WebServices的一个问题。
我知道可以通过添加WEB引用,然后建立对象,在使用,
可是如果WEBSERVICES的地址变了,是不是就要把程序重新编译一下吗?
能不能在代码中可以修改webservices的地址呢

------解决方案--------------------
那要重新通过引用来调用的吧。
------解决方案--------------------
直接更新下引用的属性就行了,也就是把WEBSERVICES的新地址复制到引用的属性
------解决方案--------------------
也可以根据IP地址来动态调用WebService的,不过要用到反射机制,来动态的获取WebService中的类名和方法名。
------解决方案--------------------
动态调用WebService类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web.Services.Description;
using System.IO;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

namespace MyInvoke
{
class InvokeWebServiceByIP
{
private static string url1 = "http:// ";
private static string url2 = ":4191/WebSiteSample/Service.asmx ";
private static string mynamespace= "MyWebService ";
private static string classname= "Service ";
public static object InvokeWebservice(string ip,string methodname, object[] args)
{
try
{
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url1+ip+url2+ "?WSDL ");
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, " ", " ");
CodeNamespace cn = new CodeNamespace(mynamespace);
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)
{
StringBuilder sb = new StringBuilder();
foreach (CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(Environment.NewLine);
}
throw new Exception(sb.ToString());
}
Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(mynamespace + ". " + classname, true, true);
object obj = Activator.CreateInstance(t);
MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
}
}
------解决方案--------------------