问题
I have code that allows me to dynamically call a web service at runtime for a given url, service name, method name, and arguments. The problem comes when the WSDL I am trying to compile contains the <import namespace="..." location="..."/>
tag. It throws the following error:
Service Description with namespace ... is missing
Presumably I need to first compile the referenced WSDL from the import tag. How should I go about this keeping in mind that the referenced WSDL could also reference another WSDL? Below is the code I am using.
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;
}
回答1:
A bit late perhaps but for google searchers not bad. You have to flatten your xsd files. Parse them and look for the import part. Take this import part and add the file found at the location path of the import. This should get you started: http://arstechnica.com/civis/viewtopic.php?f=20&t=180943
来源:https://stackoverflow.com/questions/11550077/dynamically-invoke-a-web-service-at-runtime