我需要创建多个Web服务的动态引用,并使用它发送一些值。
答案 0 :(得分:2)
要真正充满活力,你必须做三件事:
1)从Web服务获取服务描述(wsdl) 2)从服务描述中动态生成代理代码 3)编译代码并在应用程序中公开它 - 通常通过反射或某种动态脚本接口。
下面的代码片段来自我很久以前做过的一些实验。它不是生产代码,也不会编译,但如果这是你想要的方向,那么应该给你一个良好的开端。
不包括步骤(3)。生成的代码可以使用System.CodeDom.Compiler命名空间中提供的类进行编译。
Uri uri = new Uri(_Url + "?wsdl");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AllowAutoRedirect = true;
request.PreAuthenticate = false;
if (_User.Length > 0)
{
request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential(_User, _Password, _Domain);
}
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (System.Net.WebException wex)
{
response = wex.Response;
}
catch (Exception ex)
{
}
Stream requestStream = response.GetResponseStream();
ServiceDescription sd = ServiceDescription.Read(requestStream);
_ReferenceName = _Namespace + "." + sd.Services[0].Name;
ServiceDescriptionImporter Importer = new ServiceDescriptionImporter();
Importer.AddServiceDescription(sd, string.Empty, string.Empty);
Importer.ProtocolName = "Soap12";
Importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;
CodeNamespace nameSpace = new CodeNamespace(_Namespace);
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(nameSpace);
ServiceDescriptionImportWarnings warnings = Importer.Import(nameSpace, ccu);
if (warnings == 0)
{
StringWriter sw = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BlankLinesBetweenMembers = false;
options.BracingStyle = "C";
prov.GenerateCodeFromNamespace(nameSpace, sw, options);
_ProxySource = sw.ToString();
sw.Close();
}
答案 1 :(得分:-1)