在工作中经常用到webservice,在.net 开发中经常用到webservice,在java开发经常用到cxf.

  今天闲置没事就介绍下 .net webservice中常用到 soapheader token验证和重载。当然在正常使用中不太建议使用重载。

下面的列表概述接收和处理 SOAP 标头的基本步骤:

  1. 创建一个从 SoapHeader 派生的类,表示传入 SOAP 标头的数据。

    

using System.Web.Services.Protocols;

namespace WService
{
/// <summary>
/// Fireran
/// </summary>
public class MySoapHeader : SoapHeader
{ public MySoapHeader()
{ } /// <summary>
/// username
/// </summary>
public string UserName { get; set; } /// <summary>
/// ip
/// </summary>
public string Ip { get; set; } /// <summary>
/// token
/// </summary>
public string Token { get; set; }
}
}

  2. XML Web services 方法将 myHeader 成员指定为 MemberName 属性,接收 XML Web services 方法的 MyHeader SOAP 标头的内容。

     

  private MySoapHeader _mySoapHeader;
public MySoapHeader mySoapHeader
{
get { return _mySoapHeader; }
set { _mySoapHeader = value; }
}

        [WebMethod]
[SoapHeader("mySoapHeader")]
public string GetSayHello(long id)
{
string result = "";
if (mySoapHeader==null)
{
result = "token is nulll";
}
else
{
if (mySoapHeader.Token.Equals(""))
{
result = "hello world" + id;
}
else
{
result = "token is err";
}
} return result; }

   3. 发布webservice  利用wsdl 工具生成代理类

//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:2.0.50727.5466
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------ using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization; //
// 此源代码由 wsdl 自动生成, Version=2.0.50727.3038。
// /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="FireRanSoap", Namespace="http://fireran.org/")]
public partial class FireRan : System.Web.Services.Protocols.SoapHttpClientProtocol { private System.Threading.SendOrPostCallback HelloWorldOperationCompleted; private MySoapHeader mySoapHeaderValueField; private System.Threading.SendOrPostCallback GetSayHelloOperationCompleted; private System.Threading.SendOrPostCallback GetSayHello1OperationCompleted; /// <remarks/>
public FireRan() {this.Url = "http://localhost:54540/FireRan.asmx";
} public MySoapHeader MySoapHeaderValue {
get {
return this.mySoapHeaderValueField;
}
set {
this.mySoapHeaderValueField = value;
}
} /// <remarks/>
public event HelloWorldCompletedEventHandler HelloWorldCompleted; /// <remarks/>
public event GetSayHelloCompletedEventHandler GetSayHelloCompleted; /// <remarks/>
public event GetSayHello1CompletedEventHandler GetSayHello1Completed; /// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://fireran.org/HelloWorld", RequestNamespace="http://fireran.org/", ResponseNamespace="http://fireran.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string HelloWorld() {
object[] results = this.Invoke("HelloWorld", new object[]);
return ((string)(results[]));
} /// <remarks/>
public System.IAsyncResult BeginHelloWorld(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("HelloWorld", new object[], callback, asyncState);
} /// <remarks/>
public string EndHelloWorld(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[]));
} /// <remarks/>
public void HelloWorldAsync() {
this.HelloWorldAsync(null);
} /// <remarks/>
public void HelloWorldAsync(object userState) {
if ((this.HelloWorldOperationCompleted == null)) {
this.HelloWorldOperationCompleted = new System.Threading.SendOrPostCallback(this.OnHelloWorldOperationCompleted);
}
this.InvokeAsync("HelloWorld", new object[], this.HelloWorldOperationCompleted, userState);
} private void OnHelloWorldOperationCompleted(object arg) {
if ((this.HelloWorldCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.HelloWorldCompleted(this, new HelloWorldCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
} /// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("MySoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://fireran.org/SayHello", RequestElementName="SayHello", RequestNamespace="http://fireran.org/", ResponseElementName="SayHelloResponse", ResponseNamespace="http://fireran.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("SayHelloResult")]
public string GetSayHello(long id) {
object[] results = this.Invoke("GetSayHello", new object[] {
id});
return ((string)(results[]));
} /// <remarks/>
public System.IAsyncResult BeginGetSayHello(long id, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetSayHello", new object[] {
id}, callback, asyncState);
} /// <remarks/>
public string EndGetSayHello(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[]));
} /// <remarks/>
public void GetSayHelloAsync(long id) {
this.GetSayHelloAsync(id, null);
} /// <remarks/>
public void GetSayHelloAsync(long id, object userState) {
if ((this.GetSayHelloOperationCompleted == null)) {
this.GetSayHelloOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSayHelloOperationCompleted);
}
this.InvokeAsync("GetSayHello", new object[] {
id}, this.GetSayHelloOperationCompleted, userState);
} private void OnGetSayHelloOperationCompleted(object arg) {
if ((this.GetSayHelloCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSayHelloCompleted(this, new GetSayHelloCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
} /// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("MySoapHeaderValue")]
[System.Web.Services.WebMethodAttribute(MessageName="GetSayHello1")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://fireran.org/SayHello1", RequestElementName="SayHello1", RequestNamespace="http://fireran.org/", ResponseElementName="SayHello1Response", ResponseNamespace="http://fireran.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("SayHello1Result")]
public string GetSayHello(int id, int name) {
object[] results = this.Invoke("GetSayHello1", new object[] {
id,
name});
return ((string)(results[]));
} /// <remarks/>
public System.IAsyncResult BeginGetSayHello1(int id, int name, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetSayHello1", new object[] {
id,
name}, callback, asyncState);
} /// <remarks/>
public string EndGetSayHello1(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[]));
} /// <remarks/>
public void GetSayHello1Async(int id, int name) {
this.GetSayHello1Async(id, name, null);
} /// <remarks/>
public void GetSayHello1Async(int id, int name, object userState) {
if ((this.GetSayHello1OperationCompleted == null)) {
this.GetSayHello1OperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSayHello1OperationCompleted);
}
this.InvokeAsync("GetSayHello1", new object[] {
id,
name}, this.GetSayHello1OperationCompleted, userState);
} private void OnGetSayHello1OperationCompleted(object arg) {
if ((this.GetSayHello1Completed != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSayHello1Completed(this, new GetSayHello1CompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
} /// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
} /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://fireran.org/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://fireran.org/", IsNullable=false)]
public partial class MySoapHeader : System.Web.Services.Protocols.SoapHeader { private string userNameField; private string passWordField; private string tokenField; private System.Xml.XmlAttribute[] anyAttrField; /// <remarks/>
public string UserName {
get {
return this.userNameField;
}
set {
this.userNameField = value;
}
} /// <remarks/>
public string PassWord {
get {
return this.passWordField;
}
set {
this.passWordField = value;
}
} /// <remarks/>
public string Token {
get {
return this.tokenField;
}
set {
this.tokenField = value;
}
} /// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr {
get {
return this.anyAttrField;
}
set {
this.anyAttrField = value;
}
}
} /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
public delegate void HelloWorldCompletedEventHandler(object sender, HelloWorldCompletedEventArgs e); /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class HelloWorldCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal HelloWorldCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
} /// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[]));
}
}
} /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
public delegate void GetSayHelloCompletedEventHandler(object sender, GetSayHelloCompletedEventArgs e); /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSayHelloCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSayHelloCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
} /// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[]));
}
}
} /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
public delegate void GetSayHello1CompletedEventHandler(object sender, GetSayHello1CompletedEventArgs e); /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSayHello1CompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSayHello1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
} /// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[]));
}
}
}

  4. 在代理类中添加 token 信息  修改代理类中的构造方法 如下

public FireRan() {
  MySoapHeaderValue = new MySoapHeader();
  this.MySoapHeaderValue.Token = "123456";
  this.Url = "http://localhost:54540/FireRan.asmx";
}

    

  5. 添加测试类进行测试

 [TestFixture]
public class FireRanTest
{
[Test]
public void Read()
{
using(FireRan fireRan = new FireRan())
{
Console.Write(fireRan.GetSayHello());
} }
}

    6. 运行结果

  

  在项目中为了服务安全对token和ip进行授权是很有必要的。但是在项目中有发现token 和 ip 很难精确的控制服务的访问。建议在实际开发中可以根据自己业务添加动态的验证方式,和每个业务独立的业务类型。这样可以更加精确的控制访问着的访问权限和权限降级。

  

webservice 第一节 .net SoapHeader验证的更多相关文章

  1. .net SoapHeader验证

    .net SoapHeader验证 在工作中经常用到webservice,在.net 开发中经常用到webservice,在java开发经常用到cxf. 今天闲置没事就介绍下 .net webserv ...

  2. C#访问Java的WebService添加SOAPHeader验证的问题

    原文:C#访问Java的WebService添加SOAPHeader验证的问题 这两天做与公司OA的接口,发现C#访问Java的WebService需要提供一个SOAP的头验证信息,但是WebServ ...

  3. C#调用Java的WebService添加SOAPHeader验证(2)

    C#调用Java的WebService添加SOAPHeader验证 上一篇链接如上,更像是 Net下采用GET/POST/SOAP方式动态调用WebService的简易灵活方法(C#) 来处理xml, ...

  4. C#调用Java的WebService添加SOAPHeader验证

    C#调用Java的WebService添加SOAPHeader验证(2) 1.问题描述 调用的Java的webservice string Invoke(string func, string req ...

  5. .net 客户端调用java或.net webservice进行soapheader验证

    .net 客户端调用java或.net webservice进行soapheader验证 最近项目中有业务需要跨平台调用web服务,客户端和服务器之间采用非对称加密来保证数据的安全性,webservi ...

  6. ASP.NET MVC深入浅出(被替换) 第一节: 结合EF的本地缓存属性来介绍【EF增删改操作】的几种形式 第三节: EF调用普通SQL语句的两类封装(ExecuteSqlCommand和SqlQuery ) 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法 第六节: EF高级属性(二) 之延迟加载、立即加载、显示加载(含导航属性) 第十节: EF的三种追踪

    ASP.NET MVC深入浅出(被替换)   一. 谈情怀-ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态 ...

  7. ASP.NET中WebService的两种身份验证方法

    一.通过SOAP Header身份验证 此方法是通过设置SOAP Header信息来验证身份,主要通过以下几步: 1.在服务端实现一个SOAP Header类 public class Credent ...

  8. WebService第一天

    WebService第一天 [课程安排]: 整体安排:2天: 第一天:webservice入门,JDK规范和实现:jax-ws,相关概念 第二天:CXF框架,和spring的集成开发.Hessian的 ...

  9. 第一节:.Net版基于WebSocket的聊天室样例

    一. 说在前面的话 该篇文章为实时通讯系列的第一节,基于WebSocket编写了一个简易版聊天样例,主要作用是为引出后面SignalR系列的用法及其强大方便之处,通过这个样例与后续的SignalR对比 ...

随机推荐

  1. 【百度地图API】暑假放假回老家——城市切换功能

    原文:[百度地图API]暑假放假回老家--城市切换功能 任务描述: 酸奶小妹放寒假啦,要从北京呼啦一下飞回重庆呢.现在百度地图API上不能直接切换城市,怎么办呢? 如何实现: 利用API先搜索到要去城 ...

  2. Linux-常用命令1---对文件进行查看、复制、移动和分割

    基于Linux的操作系统是一种自由和开放源代码的类UNIX操作系统. Linux的几大特点决定了它的不可代替和无法超越性: (1)免费的/开源的:(2)支持多线程/多用户: (3)安全性好; (4)对 ...

  3. Android开展Exception:ActivityNotFoundException: Unable to find explicit activity class

    project出现在一个以上的activity,不AndroidManifest.xml配置,在阅读的时候,你需要知道的配置activity,使用时间或忘记配置.流汗!配置activity后proje ...

  4. 腾讯云安装openvz,高速搭建測试环境

    CSDN送了腾讯云的測试资格,准备拿来作为cici的软件公布首页,想在上面做个demo,无奈没有设备环境,于是想要用openvz来虚拟一些vps: 第一步:选择腾讯云的os模板,centos6.3 第 ...

  5. 【 D3.js 入门系列 --- 9.6 】 生产的包图

    我的个人博客是:www.ourd3js.com csdn博客为:blog.csdn.net/lzhlzz 转载请注明出处,谢谢. 打包图( Pack ).用于包括与被包括的关系,也表示各个对象的权重, ...

  6. ActionScript GifPlayer的修改

    ActionScript不能播放gif格式的图片,在做as项目的时候如果需要用到加载gif动画图片时,就需要引入第三方包. 常用的第三方包是GifPlayer,在github上可以找到该项目的源代码C ...

  7. C# 打开网页兼容Windows8.1的方式

    方法:指定浏览器 void WebWithDefaultBrower() { string name = string.Empty; try { string mainKey = @"htt ...

  8. Visual Studio Contact

    Visual Studio Contact(); 直播笔记   昨天微软干了几件了不起的事:.NET开发环境将开源.跨平台支持(Mac OS X和Linux).多设备支持(WP.Android和iOS ...

  9. 牛腩公布系统--HTTP 错误 403.14 - Forbidden

    忘了是谁说的"至理名言",做牛腩公布系统,不怕出错误,就怕出跟牛老师不一样的错误!! 刚做就開始出现各种错误了,只是话说错误越多,收获越多.把每次困难都当做历练成长的机会.不多说, ...

  10. proxool的配置

    //依赖的包:commons-logging-api-1.1.jar,commons-logging-1.0.4.jar,proxool-0.9.1.jar,proxool-cglib.jar,cgl ...