如何在合适的ASP中抛出异常或显示错误.网网络服务
本文关键字:抛出异常 显示 错误 网络服务 ASP | 更新日期: 2023-09-27 17:51:01
我正在使用ASP开发一个web服务。. NET,我不使用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; }
}
我会说,在任何错误的情况下(身份验证错误在你的情况下),而不是抛出异常,返回一个soap错误响应(WebServiceError类下面)。
public class WebServiceError
{
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
}