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

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 
{ _priority = value; }

}


public override Type ExtensionType



{


get 
{ return typeof(SessionExtension); }

}

}

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的代码。