问题
I am trying to set up a web service between a Silverlight client and a Java server. I need to send username tokens (username/password) from the Silverlight client for authentication purposes. Since this is a proof-of-concept, I want to keep things simple and use HTTP as my transport layer. However it looks like Silverlight only supports username tokens over HTTPS (Visual Studio is unable to digest the WSDL from my Java server that does username tokens over HTTP).
So my question is this: how can I add username/password information in the SOAP header sent by my Silverlight client - still using basicHttpBinding and HTTP? It does not have to be WS-Security compliant. Something as simple as this will suffice for my application:
<soapenv:Header>
<UsernameToken>
<Username>john</Username>
<Password>cool</Password>
</UsernameToken>
</soapenv:Header>
回答1:
have a look at the IClientMessageInspector. In the BeforeSendRequest
method you can add your username/password:
public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
{
request.Headers.Add(MessageHeader.CreateHeader("username", "", "user"));
request.Headers.Add(MessageHeader.CreateHeader("password", "", "pass"));
return null;
}
You have to add this to your binding:
BasicHttpMessageInspectorBinding binding = new BasicHttpMessageInspectorBinding(new MessageInspector());
var myWs= new MyWsClient(binding, new EndpointAddress(new Uri(Uri)));
来源:https://stackoverflow.com/questions/4925759/adding-custom-soap-headers-from-silverlight-client