就在现在,我得到了我的 web 服务身份验证,但我已经完成了调用 WebMethod 中的方法,如下所示:
[WebMethod]
[SoapHeader("LoginSoapHeader")]
public int findNumberByCPF(string cpf)
{
try
{
LoginAuthentication();
var retRamal = DadosSmp_Manager.RetornaRamalPorCPF(cpf);
var searchContent= String.Format("CPF[{0}]", cpf);
DadosSmp_Manager.insertCallHistory(retRamal, searchContent);
return retRamal.Ramal;
}
catch (Exception ex)
{
Log.InsertQueueLog(Log.LogType.Error, ex);
throw getException(ex.TargetSite.Name, cpf);
}
}
我现在想在不调用“LoginAuthentication()”方法的情况下验证此 WebMethod,仅使用 SOAP header - SoapHeader("LoginSoapHeader") - 位于代码上方。
那么,我的问题是如何仅使用 header 验证我的 WebMethod?
提前致谢。
最佳答案
要求是 web 服务客户端在访问 web 方法时必须提供用户名和密码。
我们将使用自定义 soap header 而不是 http header 来实现这一点
.NET 框架允许您通过从 SoapHeader 类派生来创建自定义 SOAP header ,因此我们想添加用户名和密码
using System.Web.Services.Protocols;
public class AuthHeader : SoapHeader
{
public string Username;
public string Password;
}
要强制使用我们新的 SOAP header ,我们必须将以下属性添加到方法中
[SoapHeader ("Authentication", Required=true)]
在.cs中包含类名
public AuthHeader Authentication;
[SoapHeader ("Authentication", Required=true)]
[WebMethod (Description="WebMethod authentication testing")]
public string SensitiveData()
{
//Do our authentication
//this can be via a database or whatever
if(Authentication.Username == "userName" &&
Authentication.Password == "pwd")
{
//Do your thing
return "";
}
else{
//if authentication fails
return null;
}
}
我们在 SOAP 请求中使用 soap:Header 元素进行身份验证,请不要误解与请求一起发送的 HTTP header 。 SOAP 请求类似于:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<AUTHHEADER xmlns="http://tempuri.org/">
<USERNAME>string</USERNAME>
<PASSWORD>string</PASSWORD>
</AUTHHEADER>
</soap:Header>
<soap:Body>
<SENSITIVEDATA xmlns="http://tempuri.org/" />
</soap:Body>
</soap:Envelope>
关于c# - Web 服务 header 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18089449/