Я пытаюсь вызвать webServcie через WebClient и использую ServiceDescriptionImporter
Но когда я выполню этот код --->
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit)
Я получу эту ошибку:
Не удалось импортировать пространство имен xxxx привязки xxxx "
Этот веб-сервис был предоставлен другим поставщиком. Если я позвоню в другой веб-сервис, разработанный нами, это не вызовет проблем.
Может кто-нибудь подсказать мне, как решить эту проблему?
Большое вам спасибо
private static String _UriAddress = "http://invoice.cetustek.com.tw/InvoiceEntitySync/InvoiceAPI";
static void Main(string[] args)
{
object[] objectpara = new string[5] { "107","11-12", "73680784","chunmei001","28689155CC1F0D60A" };
object test = new object();
test = CallWebService(_UriAddress, "InvoiceAPI", "ApplyInvoiceNumber", objectpara);
String aaa= test.ToString();
}
public static Object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)
{
System.Net.WebClient client = new System.Net.WebClient();
//client.UseDefaultCredentials = true;
NetworkCredential nc = new NetworkCredential("xxx", "xxx", "xxx");
client.Proxy.Credentials = nc;
//Connect To the web service
System.IO.Stream stream = client.OpenRead(string.Format("{0}?wsdl", webServiceAsmxUrl));
//Read the WSDL file describing a service.
ServiceDescription description = ServiceDescription.Read(stream);
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
//Use SOAP 1.2. (有些Java的WebService不Support 1.2,請設成空字串
importer.ProtocolName = "SOAP";
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
//這裡取出 WebService 的參數
//判斷如果是物件或是Array的話,就透過JSON.NET來轉成WS要的物件
ParameterInfo[] pInfos = mi.GetParameters();
ArrayList newArgs = new ArrayList();
int i = 0;
foreach (ParameterInfo p in pInfos)
{
Type pType = p.ParameterType;
if (pType.IsPrimitive || pType == typeof(string))
{
newArgs.Add(args[i]);
}
else
{
//透過 JSON.NET 轉成物件
var argObj = JsonConvert.DeserializeObject((string)args[i], pType);
newArgs.Add(argObj);
}
i += 1;
}
return mi.Invoke(wsvcClass, newArgs.ToArray());
}
else
{
return null;
}
}
}
}