其实利用的都是前人的成果:C# – Dynamically Invoke Web Service At Runtime

这个文章的问题是没有提及需要认证的时候怎么办,但是后面很多回帖都问到了,总结下:

在读取WSDL的时候有几种方式,我使用的是:

WebClient client = new WebClient();

if (_needCredential)
{
client.Credentials = _credential;
}
Stream stream = client.OpenRead(WSDL);
XmlTextReader xmlreader = new XmlTextReader(stream);

//XmlTextReader xmlreader = new XmlTextReader(Uri);
ServiceDescriptionImporter descriptionImporter = BuildServiceDescriptionImporter(xmlreader);
Assembly library = CompileAssembly(descriptionImporter);

在真正生成WebService的Instance以后,需要设置Instance的几个Property:

if (_needCredential)
{
PropertyInfo preAuthenticate = GetRealType().GetProperty(“PreAuthenticate”);
preAuthenticate.SetValue(Result, true, null);
PropertyInfo url = GetRealType().GetProperty(“Url”);
url.SetValue(Result, Url, null);
CredentialCache cache = new CredentialCache();
Uri uri = new Uri(Url);
cache.Add(uri, “Basic”, _credential);
PropertyInfo credentials = GetRealType().GetProperty(“Credentials”);
credentials.SetValue(Result, cache, null);
}

(Visited 519 times, 1 visits today)