我有一个 WCF 服务,我想在运行时调用它...
如果我执行相同的代码而不是 WCF(.svc) 如果我调用 (.asmx) 我可以通过并获得结果...但是这里 WCF 失败了
private void button1_Click(object sender, EventArgs e)
{
string WebserviceUrl = "http://localhost:90/service1/service1.svc";
string serviceName = Service1;
string methodName = GetData;
string[] arArguments = new string[2];
arArguments[0] = 2 ;
string sData =CallWebService(WebserviceUrl, serviceName, methodName, arArguments);
if (!string.IsNullOrEmpty(sData))
MessageBox.Show(sData + "\tData Available");
else
MessageBox.Show(sData + "\tData not Available");
}
[SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
private string CallWebService(string WebserviceUrl, string serviceName, string methodName, string[] arArguments)
{
System.Net.WebClient client = new System.Net.WebClient();
System.IO.Stream stream = client.OpenRead(WebserviceUrl + "?wsdl");
ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
importer.AddServiceDescription(description, null, null);
importer.Style = ServiceDescriptionImportStyle.Client;
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);
ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
if (warning == 0) // If Successfull
{
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
if (results.Errors.Count > 0) // Error Part
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");
}
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Name;
}
else
{
return null;
}
}
如何实现这个......