How to pass an exception or show an error in a suitable ASP.NET web service
I am developing a web service using ASP.NET. I am not using WCF. I am using legacy web service technologies. But I have a big problem. I want clients to pass credentials in the soap header for every request in order to validate them. I have created an authentication function. I don't want to call this function in every function of my service class. So I call this function inside the constructor of my service class. If the check fails. I want to throw an exception. But I know this is not good for throwing exceptions in a webservice. So please tell me the most efficient way to throw exceptions in a .NET webservice and any suggestions for improving my code. Below is my code.
My service code
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;
}
}
My Authentication Header Class
public class AuthHeader : SoapHeader
{
public string Username { get; set; }
public string Password { get; set; }
}
source to share
I would say that in case of any error (authentication error in your case), but rather throwing exceptions, a soapy error response is returned (WebServiceError class below).
public class WebServiceError
{
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
}
source to share