如何在ASP.NET Web服务中适当地引发异常或显示错误

问题描述 投票:3回答:1

我正在使用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; }
}
c# web-services asmx
1个回答
0
投票

[我会说如果发生任何错误(在您的情况下为Authentication Error),而不是引发异常,则返回了肥皂错误响应(下面的WebServiceError类)。

public class WebServiceError
{
    public string ErrorCode { get; set; }
    public string ErrorMessage { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.