gpt4 book ai didi

c# - 在运行时动态调用 Web 服务

转载 作者:太空宇宙 更新时间:2023-11-03 16:28:51 24 4
gpt4 key购买 nike

我的代码允许我在运行时针对给定的 URL、服务名称、方法名称和参数动态调用 Web 服务。当我尝试编译的 WSDL 包含 <import namespace="..." location="..."/> 时,问题就来了标签。它抛出以下错误:

Service Description with namespace ... is missing

大概我需要先从导入标签编译引用的 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;
}

最佳答案

也许有点晚了,但对于谷歌搜索者来说还不错。您必须展平您的 xsd 文件。解析它们并寻找导入部分。获取此导入部分并添加在导入位置路径中找到的文件。这应该让你开始: http://arstechnica.com/civis/viewtopic.php?f=20&t=180943

关于c# - 在运行时动态调用 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11550077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com