【问题标题】:How to throw exception or show error in suitable in ASP.NET webservice如何在 ASP.NET webservice 中适当地抛出异常或显示错误
【发布时间】: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 无法轻松做到这一点。

标签: c# web-services asmx


【解决方案1】:

我会说,如果出现任何错误(在您的情况下是 Authentication Error)而不是抛出异常,则返回一个肥皂错误响应(下面的 WebServiceError 类)。

public class WebServiceError
{
    public string ErrorCode { get; set; }
    public string ErrorMessage { get; set; }
}

【讨论】:

  • 但是我在里面扔了 constructor 。因为我不想在每个方法中都调用那个函数。
  • 所以这个不能用。
猜你喜欢
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 2017-02-16
  • 2010-12-01
相关资源
最近更新 更多