WebService – 2.动态调用WebService

时间:2021-07-26 15:10:44

在本节课程中,将演示如何通过程序动态添加、调用、编译、执行WebService并返回结果。

WebService动态调用示意图

WebService – 2.动态调用WebService

WebService相关知识
代码文档对象模型CodeDom的使用
编程使用C#编译器
反射

1.先建动态调用辅助类 WebServiceHelper.cs

WebService – 2.动态调用WebService

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Net;
using System.Web.Services;
using System.Web.Services.Description;
using Microsoft.CSharp; namespace InvokeWebService
{
public static class WebServiceHelper
{
/// <summary>
/// 动态调用WebService
/// </summary>
/// <param name="Url">WebService地址</param>
/// <param name="methodname">WebService方法名(模块名)</param>
/// <param name="args">调用接口的参数列表</param>
/// <returns></returns>
public static object InvokeWebService(string Url,string methodname,object[] args)
{
return InvokeWebService(Url, null, methodname, args);
} /// <summary>
/// 动态调用WebService
/// </summary>
/// <param name="Url">WebService地址</param>
/// <param name="className">类名</param>
/// <param name="methodname">WebService方法名</param>
/// <param name="args">调用接口的参数列表</param>
/// <returns></returns>
public static object InvokeWebService(string Url, string className, string methodname, object[] args)
{
string @namespace = "ServiceBase.WebSerice.DynamicWebLoad";
if (className == null || className == "")
{
className = WebServiceHelper.GetClassName(Url);
}
//1.服务描述语言(WSDL)
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(Url + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
CodeNamespace cn = new CodeNamespace(@namespace); //2.生成客户端代理类代码
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
CSharpCodeProvider csc = new CSharpCodeProvider();
ICodeCompiler icc = csc.CreateCompiler();
//3.设定编译器的参数
CompilerParameters cplist = new CompilerParameters();
cplist.GenerateExecutable=false;
cplist.GenerateInMemory = true;
cplist.ReferencedAssemblies.Add("System.dll");
cplist.ReferencedAssemblies.Add("System.XML.dll");
cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
cplist.ReferencedAssemblies.Add("System.Data.dll");
//4.变异代理类
CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
if (true==cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new StringBuilder();
foreach (CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
//生成代理实例,并调用方法
System.Reflection.Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(@namespace + "." + className, true, true);
object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
} //获取类名
private static string GetClassName(string url)
{
string[] parts = url.Split('/');
string[] pps = parts[parts.Length - ].Split('.');
return pps[];
}
}
}

WebServiceHelper.cs

2.建WebService,  Service1.asmx

WebService – 2.动态调用WebService

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services; namespace InvokeServices
{
/// <summary>
/// Service1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{ [WebMethod]
public string HelloWorld(string Temp1,string Temp2)
{
return string.Format("参数1:{0},参数2:{1}", Temp1, Temp2);
}
}
}

Service1.asmx

3.建应用程序

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
string url = "http://localhost:4547/Service1.asmx";
string[] args = new string[];
args[] = this.textBox1.Text;
args[] = this.textBox2.Text;
object result = InvokeWebService.WebServiceHelper.InvokeWebService(url, "HelloWorld", args); this.textBox3.Text = result.ToString();
}
}
}

Form1.cs

WebService – 2.动态调用WebService