Search code examples
c#asmxsoapexceptionsoap-extension

ASMX Web Service: How to throw soap exception from asmx service which i like to capture from client side


I want if client send wrong credentials then service throw soap exception but I tried but still no luck.

see my updated code from here https://github.com/karlosRivera/EncryptDecryptASMX

Anyone can download my code and run in their PC to capture the problem.

see this area

[AuthExtension]
[SoapHeader("CredentialsAuth", Required = true)]
[WebMethod]
public string Add(int x, int y)
{
    string strValue = "";
    if (CredentialsAuth.UserName == "Test" && CredentialsAuth.Password == "Test")
    {
        strValue = (x + y).ToString();
    }
    else
    {
        throw new SoapException("Unauthorized", SoapException.ClientFaultCode);

    }
    return strValue;
}

For this line throw new SoapException("Unauthorized", SoapException.ClientFaultCode);

The response XML body is not getting change which I have seen from my soapextension process message function.

So I have two issues now

1) I want throw SoapException from service for which soap response need to be changed.

2) From client side I need to catch the SoapException

Please view my latest code from the link and tell me what to change. thanks


Solution

  • Another option is to avoid sending SoapExceptions, but more complex objects that embed error semantics. E.g.

    [Serializable]
    class Result<T>
    {
        public bool IsError { get; set; }
        public string ErrorMessage { get; set; }
    
        public T Value { get; set; }
    }
    

    In this case your method could look like this:

    [AuthExtension]
    [SoapHeader("CredentialsAuth", Required = true)]
    [WebMethod]
    public Result<string> Add(int x, int y)
    {
        string strValue = "";
        if (CredentialsAuth.UserName == "Test" && CredentialsAuth.Password == "Test")
        {
            return new Result<string> { Value = (x + y).ToString() };
        }
        else
        {
            return new Result<string> { IsError = true, ErrorMessage = $"Unauthorized -  {SoapException.ClientFaultCode}" };
        }
    }
    

    Result can be developed to include an array of field/input errors to return more precise error messages related to incorrect input parameter values.