我需要从C#.net控制台应用程序调用SOAP Web服务。该服务需要在调用中使用自定义UsernameToken标头。我可以像这样在app.config文件中添加这个标题,它可以工作:
<headers>
<wsse:Security mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>username</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</headers>
但是,我实际上需要在循环中多次进行此调用,每次都传入不同的用户名和密码。我怎样才能做到这一点?我似乎无法从代码中访问此值。
答案 0 :(得分:0)
我有一些来自我的项目的示例代码:
public static MessageHeader<SecurityHeaderType> GetSecurityHeader(string userName, string passWord, string nonce)
{
if (string.IsNullOrEmpty(userName)
{
userName = string.Empty;
}
if (string.IsNullOrEmpty(passWord))
{
passWord = string.Empty;
}
if (string.IsNullOrEmpty(nonce))
{
nonce = string.Empty;
}
var usernameToken = new UsernameToken();
var securityHeader = new SecurityHeaderType { UsernameToken = usernameToken };
// ReSharper disable once SpecifyACultureInStringConversionExplicitly
string now = DateTime.Now.ToString();
var tokenManager = new UsernameTokenManager();
var passwordDigest = tokenManager.CreatePasswordDigest(Convert.FromBase64String(nonce), now, passWord);
securityHeader.UsernameToken.Created = now;
securityHeader.UsernameToken.Nonce = nonce;
securityHeader.UsernameToken.Password = passwordDigest;
securityHeader.UsernameToken.Username = userName;
var header = new MessageHeader<SecurityHeaderType> { Content = securityHeader, Actor = "" };
return header;
}
Public void CallService(){
const string userName = "username";
const string passWord = "password";
const string nonce = "nonce";
var securityHeader = SecurityHeaderHelper.GetSecurityHeader(userName, passWord, nonce);
using (new OperationContextScope(_client.InnerChannel))
{
var untypedSecurityHeader = securityHeader.GetUntypedHeader("Security", Constants.SecurityHeaderWSSE);
OperationContext.Current.OutgoingMessageHeaders.Add(untypedSecurityHeader);
var dummyRequest = new DummyRequest();
try
{
var testResponse = _client.Call(dummyRequest);
}
catch (Exception exp)
{
Assert.Fail(exp.Message);
}
}
}}