我的代码允许我在运行时为给定的 url、服务名称、方法名称和参数动态调用 Web 服务。当我尝试编译的 WSDL 包含<import namespace="..." location="..."/>
标记时,问题就出现了。它抛出以下错误:
带有命名空间...的服务描述丢失
大概我需要先从导入标签编译引用的 WSDL。记住引用的 WSDL 也可以引用另一个 WSDL,我应该如何处理?下面是我正在使用的代码。
public static object CallWebService(string url, string serviceName, string methodName, string userName, string password, ServiceDescription wsdl, ILogger logger, object[] args)
{
var client = new WebClient();
if (userName.Length > 0)
{
client.Credentials = new NetworkCredential(userName, password);
}
var stream = client.OpenRead(url + "?wsdl");
if (stream != null)
{
var description = ServiceDescription.Read(stream);
wsdl = description;
var importer = new ServiceDescriptionImporter
{
ProtocolName = "Soap12",
Style = ServiceDescriptionImportStyle.Client,
CodeGenerationOptions = CodeGenerationOptions.GenerateProperties
};
importer.AddServiceDescription(wsdl, null, null);
var nameSpace = new CodeNamespace();
var unit = new CodeCompileUnit();
unit.Namespaces.Add(nameSpace);
**var warning = importer.Import(nameSpace, unit);** // Error occurs here
if (warning == 0)
{
var provider = CodeDomProvider.CreateProvider("CSharp");
var assemblyReferences = new[] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
var parameters = new CompilerParameters(assemblyReferences);
var results = provider.CompileAssemblyFromDom(parameters, unit);
if (results.Errors.Count > 0)
{
logger.Info("Compiler errors: " + results.Errors.Count);
foreach (var error in results.Errors)
{
logger.Info(error.ToString());
}
throw new Exception("Compile Error Occured calling webservice.");
}
var service = results.CompiledAssembly.CreateInstance(serviceName);
if (service != null)
{
var methods = service.GetType().GetMethods();
var method = service.GetType().GetMethod(methodName);
if (method == null)
{
var message = "Method: " + methodName + " is invalid. Valid Methods are: ";
message = methods.Aggregate(message, (current, methodInfo) => current + methodInfo.Name + "; ");
throw new Exception(message);
}
return method.Invoke(service, args);
}
logger.Info("Service invocation error. ServiceName provided: " + serviceName);
return null;
}
return null;
}
return null;
}