微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在SOAP Header中携带认证ID的WebService实例

通过在SOAP Header中携带认证ID,可避免调用WebService时对HTTP Cookie的依赖,实现自定义的认证和Session管理。具体实现方法如下:

  • 自定义SOAP Header

public   class  SessionHeader : SoapHeader

{

    
public string SessionId;

}
  • 扩展属性的定义

    [AttributeUsage(AttributeTargets.Method)]

    
public   class  SessionExtensionAttribute : SoapExtensionAttribute

    
{

        
int _priority = 1;


        
public override int Priority

        
{

            
get return _priority; }

            
set 


        }


        
public override Type ExtensionType

        
{

            
get return typeof(SessionExtension); }

        }

    }
  •  SOAP Header的处理

     public   class  SessionExtension : SoapExtension

    
{

        
public override void ProcessMessage(SoapMessage message)

        
{

            
if (message.Stage == SoapMessageStage.AfterDeserialize)

            
{

                
//Check for an SessionHeader containing valid credentials

                foreach (SoapHeader header in message.Headers)

                
{

                    
if (header is SessionHeader)

                    
{

                        SessionHeader credentials 
= (SessionHeader)header;

                        
// Check SessionId


                        
break;

                    }

                }


                
// Fail the call if we get to here. Either the header

                
// isn't there or it contains invalid credentials.

                throw new SoapException("Invalid SessionId",

                    SoapException.ClientFaultCode);

            }

        }


        
public override Object GetInitializer(Type type)

        
{

            
return GetType();

        }


        
public override Object GetInitializer(LogicalMethodInfo info,

            SoapExtensionAttribute attribute)

        
{

            
return null;

        }


        
public override void Initialize(Object initializer)

        
{

        }

    }

 

  •  在WebService的WebMethod方法中添加属性

[WebService(Namespace  =   " http://tempuri.org/ " )]

[WebServiceBinding(ConformsTo 
=  WsiProfiles.BasicProfile1_1)]

public   class  EDocService : System.Web.Services.WebService  {

    
public SessionHeader Credentials;


    [SessionExtension]

    [SoapHeader(
"Credentials")]

    [WebMethod]

    
public void Method1()

    
{

        
string sid = credentials.sessionid;

    }

}


当调用Method1时,如果SOAP Header中没有合法的SessionID,则调用方会收到HTTP 500错误,无法执行Method1的代码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐