【发布时间】:2015-08-10 18:36:29
【问题描述】:
我正在使用 ASP.NET 开发 Web 服务,但我没有使用 WCF。我正在使用旧版 Web 服务技术。我希望客户端在每个请求的soap标头中传递凭据以验证它们。我创建了一个身份验证功能。我不想在我的服务类的每个函数中调用该函数。
所以我在服务类的构造函数中调用该函数。如果验证失败,我想抛出异常。但我知道这不是在 Web 服务中引发异常的合适方式。在 .NET Web 服务中引发异常的最有效方法是什么?
下面是我的代码:
我的服务代码
public class math : System.Web.Services.WebService
{
public AuthHeader Authentication;
public math()
{
if(Authentication==null || Authentication.Username!="username" || Authentication.Password!="mypassword")
{
throw new Exception("Authentication failed");
}
}
[WebMethod]
[SoapHeader("Authentication",Required=true)]
public int Sum(int num1,int num2)
{
return num1 + num2;
}
}
我的认证头类
public class AuthHeader : SoapHeader
{
public string Username { get; set; }
public string Password { get; set; }
}
【问题讨论】:
-
有理由不使用WCF吗? ASMX 不应该用于新的开发。除此之外,如果您正在使用 WCF,您可以将特定的 SOAP 错误返回给您的客户端。使用 ASMX 无法轻松做到这一点。
-
@waiyan 试试这个msdn.microsoft.com/en-us/library/vstudio/…
标签: c# web-services asmx