封装的WebserviceHelp类:

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Web.Services.Description;
using Microsoft.CSharp;
using System.Xml.Serialization; namespace MyServiceLibrary
{
/// <summary>
/// 动态调用WebService(支持SaopHeader)
/// </summary>
public class WebServiceHelper
{
/// <summary>
/// 获取WebService的类名
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <returns>返回WebService的类名</returns>
private static string GetWsClassName(string wsUrl)
{
string[] parts = wsUrl.Split('/');
string[] pps = parts[parts.Length - ].Split('.');
return pps[];
} /// <summary>
/// 调用WebService(不带SoapHeader)
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <param name="methodName">方法名称</param>
/// <param name="args">参数列表</param>
/// <returns>返回调用结果</returns>
public static object InvokeWebService(string wsUrl, string methodName, object[] args)
{
return InvokeWebService(wsUrl, null, methodName, null, args);
} /// <summary>
/// 调用WebService(带SoapHeader)
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <param name="methodName">方法名称</param>
/// <param name="soapHeader">SOAP头</param>
/// <param name="args">参数列表</param>
/// <returns>返回调用结果</returns>
public static object InvokeWebService(string wsUrl, string methodName, SoapHeader soapHeader, object[] args)
{
return InvokeWebService(wsUrl, null, methodName, soapHeader, args);
} /// <summary>
/// 调用WebService
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <param name="className">类名</param>
/// <param name="methodName">方法名称</param>
/// <param name="soapHeader">SOAP头</param>
/// <param name="args">参数列表</param>
/// <returns>返回调用结果</returns>
public static object InvokeWebService(string wsUrl, string className, string methodName, SoapHeader soapHeader, object[] args)
{
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if ((className == null) || (className == ""))
{
className = GetWsClassName(wsUrl);
}
try
{
//获取WSDL
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(wsUrl + "?wsdl");
ServiceDescription sd = ServiceDescription.Read(stream); //配置代理ServiceDescriptionImporter数据
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
//sdi.ProtocolName = "Soap";
//sdi.Style = ServiceDescriptionImportStyle.Server;
//sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
sdi.AddServiceDescription(sd, null, null);
CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu); //CSharpCodeProvider csc = new CSharpCodeProvider();
///ICodeCompiler icc = csc.CreateCompiler();
CodeDomProvider icc = CodeDomProvider.CreateProvider("CSharp"); //设定编译参数
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"); //编译代理类
CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.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); FieldInfo[] arry = t.GetFields(); FieldInfo client = null;
object clientkey = null;
if (soapHeader != null)
{
//Soap头开始
client = t.GetField(soapHeader.ClassName + "Value"); //获取客户端验证对象
Type typeClient = assembly.GetType(@namespace + "." + soapHeader.ClassName); //为验证对象赋值
clientkey = Activator.CreateInstance(typeClient); foreach (KeyValuePair<string, object> property in soapHeader.Properties)
{
typeClient.GetField(property.Key).SetValue(clientkey, property.Value);
}
//Soap头结束
} //实例类型对象
object obj = Activator.CreateInstance(t); if (soapHeader != null)
{
//设置Soap头
client.SetValue(obj, clientkey);
} System.Reflection.MethodInfo mi = t.GetMethod(methodName); return mi.Invoke(obj, args);
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
} /// <summary>
/// SOAP头
/// </summary>
public class SoapHeader
{
/// <summary>
/// 构造一个SOAP头
/// </summary>
public SoapHeader()
{
this.Properties = new Dictionary<string, object>();
} /// <summary>
/// 构造一个SOAP头
/// </summary>
/// <param name="className">SOAP头的类名</param>
public SoapHeader(string className)
{
this.ClassName = className;
this.Properties = new Dictionary<string, object>();
} /// <summary>
/// 构造一个SOAP头
/// </summary>
/// <param name="className">SOAP头的类名</param>
/// <param name="properties">SOAP头的类属性名及属性值</param>
public SoapHeader(string className, Dictionary<string, object> properties)
{
this.ClassName = className;
this.Properties = properties;
} /// <summary>
/// SOAP头的类名
/// </summary>
public string ClassName { get; set; } /// <summary>
/// SOAP头的类属性名及属性值
/// </summary>
public Dictionary<string, object> Properties { get; set; } /// <summary>
/// 为SOAP头增加一个属性及值
/// </summary>
/// <param name="name">SOAP头的类属性名</param>
/// <param name="value">SOAP头的类属性值</param>
public void AddProperty(string name, object value)
{
if (this.Properties == null)
{
this.Properties = new Dictionary<string, object>();
}
Properties.Add(name, value);
}
}
} }

使用方法介绍:
如果soapheader是这种方式:

public class MySoapHeader : System.Web.Services.Protocols.SoapHeader
{
private string userID = string.Empty;
private string userPW = string.Empty; public string UserId
{
get { return userID; }
set { userID = value; }
}
public string UserPW
{
get { return userPW; }
set { userPW = value; }
}
}

调用上面ServiceHelper方式如下:

WebServiceHelper.SoapHeader header = new WebServiceHelper.SoapHeader("MySoapHeader");
header.AddProperty("UserId", "admin");
header.AddProperty("UserPW", "admin");
object r = WebServiceHelper.InvokeWebService("http://localhost:9015/WebService1.asmx","HelloWorld2",header,null);
Console.WriteLine(r.ToString());
Console.ReadKey();

动态调用Webservice 支持Soapheader身份验证(转)的更多相关文章

  1. 调用WebService时加入身份验证,以拒绝未授权的访问

    众所周知,WebService是为企业需求提供的在线应用服务,其他公司或应用软件能够通过Internet来访问并使用这项在线服务.但在有些时候的某些应用服务不希望被未授权访问,那么此时我们可以一下几种 ...

  2. ANDROID调用webservice带soapheader验证

    最近的一个项目中调用webservice接口,需要验证soapheader,现将解决方法记录如下:(网上资料出处太多,就不做引用,原作者如看到,如有必要添加请通知) 1.先看接口 POST /webs ...

  3. 动态调用webservice及WCF服务

    动态调用web服务,该方法只针对Web service, WCF的服务不行,如果是WCF的就通过工具直接生产代理类,把代理类配置到调用的项目中,通过配置客户端的终结点动态的取实现: 通过Svcutil ...

  4. [转]Net 下采用GET/POST/SOAP方式动态调用WebService C#实现

    本文转自:http://www.cnblogs.com/splendidme/archive/2011/10/05/2199501.html 一直以来,我们都为动态调用WebService方法而烦恼. ...

  5. .Net 下采用GET/POST/SOAP方式动态调用WebService的简易灵活方法(C#) [轉]Redfox

    一直以来,我都为动态调用WebService方法而烦恼.在.Net环境下,最常用的方法就是采用代理类来调用WebService,可以通过改变代理类的Url属性来实现动态调用,但当xmlns改变时就会出 ...

  6. Atitit 动态调用webservice与客户端代理方式调用

    Atitit 动态调用webservice与客户端代理方式调用 方式1: 使用call.invoke  直接调用WSDL,缺点:麻烦,不推荐--特别是JAVA调用.NET的WS时,会有不少的问题需要解 ...

  7. 动态调用WebService(C#) (非常实用)

    通常我们在程序中需要调用WebService时,都是通过“添加Web引用”,让VS.NET环境来为我们生成服务代理,然后调用对应的Web服务.这样是使工作简单了,但是却和提供Web服务的URL.方法名 ...

  8. 动态调用webservice(部分转载)

    动态调用webservice,做个笔记: public class WSHelper { /// < summary> /// 动态调用web服务 /// < /summary> ...

  9. C# 动态调用webservice

    最近项目中,用到动态调用webservice的内容,此处记录下来,留着以后COPY(我们只需要在XML,config文件,或者数据库中配置webservice连接地址和方法名即可使用): using ...

随机推荐

  1. CSS小记

    1.元素居中 (1)水平居中:指定宽度,然后margin auto 即可 .middle{ max-width:400px; //width:400px;//当浏览器被缩小,宽度小于元素宽度时,元素会 ...

  2. JS面试题及答案总结

    1. 截取字符串abcdefg的efg  <div id="test">abcdefg</div> var mytext=document.getEleme ...

  3. 【转】websocket协议规范

    在线版目录: 1.引言——WebSocket协议翻译 2.一致性要求——WebSocket协议翻译 3.WebSocket URI——WebSocket协议翻译 4.打开阶段握手——WebSocket ...

  4. angular2怎么使用第三方的库(jquery等)

    网上找了很多教材都搜索不到该部分类型,自己测试了下写了该教程. 场景说明:项目需要使用bootstrap,众所周知bootstrap没有时间日期控件的,需要使用第三方控件,我对如何在angular2中 ...

  5. VirtualBox下安装rhel5.5 linux系统

    以前也用过VMware server和VMware workstation虚拟机,现在使用了一段时间VirtualBox,感觉它比较轻巧,很适合我,在Win7系统下用起来很方便.下面详细介绍下在Vir ...

  6. 字符串模拟赛T3

    只看我的做法就够了 #include<iostream> #include<cstdio> #include<string> #include<cstring ...

  7. thinkphp中模板继承

    模板继承是3.1.2版本添加的一项更加灵活的模板布局方式,模板继承不同于模板布局,甚至来说,应该在模板布局的上层.模板继承其实并不难理解,就好比类的继承一样,模板也可以定义一个基础模板(或者是布局), ...

  8. Truck History(prim & mst)

    Truck History Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 19772   Accepted: 7633 De ...

  9. 将DataSet(DataTable)转换成JSON格式(生成JS文件存储)

    public static string CreateJsonParameters(DataTable dt) { /**/ /**/ /**/ /* /*********************** ...

  10. [Effective JavaScript 笔记]第30条:理解prototype、getPrototypeOf和__ptoto__之间的不同

    原型包括三个独立但相关的访问器.这三个单词都是对单词prototype做了一些变化. C.prototype用于建立由new C()创建的对象的原型 Object.getPrototypeOf(obj ...