我有一个asmx Web服务和一个测试控制台应用程序。我已将Web服务引用添加到控制台应用程序并像这样调用它
Employee.Employee e = new TestService.Employee.Employee();
e.SomeMethod();
在每个Web服务调用上都有一个验证检查,看起来像这样
private bool IsUserNameTokenPresent()
{
//Get current SOAP context
SoapContext ctxt = RequestSoapContext.Current;
UsernameToken user = null;
if (ctxt == null)
{
//This request is using a different protocol other than SOAP.
return false;
}
//Iterate through all Security tokens
foreach(SecurityToken tok in ctxt.Security.Tokens)
{
if (tok is UsernameToken)
{
user = (UsernameToken)tok;
}
}
if (user == null)
return false;
return true;
}
问题:如何通过安全令牌以便我可以测试此服务。它总是空的。
答案 0 :(得分:2)
终于找到了答案。我必须手动创建自己的SOAP标头并将其与请求一起传递。这是一些代码。我必须为每次调用动态创建Nonce,如果有人想要代码,我会在这里发布。
XmlDocument doc = new XmlDocument();
doc.InnerXml = @"<?xml version='1.0' encoding='utf-8'?>
<soap:Envelope
xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'
xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'
xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'>
<soap:Header>
<wsse:Security soap:mustUnderstand='1'>
<wsse:UsernameToken wsu:Id='uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c'>
<wsse:Username>UserID</wsse:Username>
<wsse:Password>Pass</wsse:Password>
<wsse:Nonce>" + nonce + @"</wsse:Nonce>
<wsu:Created>" + date + @"</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
</soap:Header>
<soap:Body>
<FindBySelfId>
<specification>
<LastName>" + lastname + @"</LastName>
<FirstName>" + firstname + @"</FirstName>
<DateOfBirth>" + dob + @"</DateOfBirth>
<HomeZipCode>" + zip + @"</HomeZipCode>
<SSN4>" + ssn + @"</SSN4>
</specification>
</FindBySelfId >
</soap:Body>
</soap:Envelope>";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/Employee/employee.asmx");
req.Headers.Add("SOAPAction", "https://<Namespace here>");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();