Webservice返回SoapHeader
Webservice在请求中加入自定义的SoapHeader,比较常用的场景是在SoapHeader中携带用户登陆信息,由服务端进行身份验证。今天遇到一个需求,除了在请求时要携带SoapHeader外,在返回值中也要返回一个结构不同的SoapHeader对象。简单点,在参数中增加ref outHeader,也可以实现需求。但是客户的WebService接口并不是这样设计的。于是找到下面的处理方法:
定义两个SoapHeader类:
public class InSoapHeader : SoapHeader { public InSoapHeader() { } public string UserName { get; set; } public string Ip { get; set; } public string Token { get; set; } } public class OutSoapHeader : SoapHeader { public OutSoapHeader() { } public string Ip { get; set; } }
编写WebService服务:
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class WebService1 : System.Web.Services.WebService { private InSoapHeader _inSoapHeader; public InSoapHeader InSoapHeader { get { return _inSoapHeader; } set { _inSoapHeader = value; } } private OutSoapHeader _outSoapHeader=new OutSoapHeader();//给定初始值,否则在返回时会null public OutSoapHeader OutSoapHeader { get { return _outSoapHeader; } set { _outSoapHeader = value; } } [WebMethod] [SoapHeader("InSoapHeader", Direction = SoapHeaderDirection.In)] [SoapHeader("OutSoapHeader", Direction = SoapHeaderDirection.Out)] public string HelloWorld() { OutSoapHeader.Ip = "123123"; return string.Empty; } }
客户端调用程序:
private void btnCall_Click(object sender, EventArgs e) { ServiceReference1.WebService1SoapClient cli = new ServiceReference1.WebService1SoapClient(); ServiceReference1.InSoapHeader inheader = new ServiceReference1.InSoapHeader() { Ip="127.0.0.1",Token="N",UserName="N"}; ServiceReference1.OutSoapHeader outheader; string result = string.Empty; outheader=cli.HelloWorld(inheader,out result);//这时候返回值自动放到了参数中,和普通的方法还是有区别的。 System.Diagnostics.Debug.WriteLine(outheader.Ip); //输出123123 }