针对.NET平台下的WebService访问,为达到不添加引用的情况下,动态调用外部服务。
主体方法:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public class WebServiceHelper { //Calling the WebService dynamically public static T CallWebServiceDynamic<T>(string address, string serviceName, string serviceMethod, object[] args) { WebClient client = new WebClient(); System.IO.Stream stream = client.OpenRead(address); ServiceDescription description = ServiceDescription.Read(stream); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap12"; importer.AddServiceDescription(description, null, null); importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; CodeNamespace nmspace = new CodeNamespace(); CodeCompileUnit compileUnit = new CodeCompileUnit(); compileUnit.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, compileUnit); if ( warning != 0 ) { throw new Exception($"Warning:{warning}"); } CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); string[] assemblyReferences = new string[3] { "System.dll", "System.Xml.dll", "System.Web.Services.dll" }; CompilerParameters parms = new CompilerParameters(assemblyReferences); parms.GenerateExecutable = false; parms.GenerateInMemory = true; CompilerResults results = provider.CompileAssemblyFromDom(parms, compileUnit); object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName); MethodInfo method = wsvcClass.GetType().GetMethod(serviceMethod); var data = method.Invoke(wsvcClass, args); if ( data != null ) { return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(data)); } return default(T); } }
使用场景:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
string endPointAddress = ConfigurationManager.AppSettings["xxxxxx"]; public WorkPackageServiceModel[] GetMinimalWorkPackage(Guid projectItemId, string projectNumber) { return WebServiceHelper.CallWebServiceDynamic<WorkPackageServiceModel[]>(endPointAddress, "DataCenter", "GetMinimalWorkPackage", new object[] { projectItemId, projectNumber }); }
That's all!