Wednesday, October 9, 2013

Very simple.net web service exception handling


  1. Create header exception

  2. Assign header  for special web method

  3. Exception handling at client: SoapException and SoapHeaderException



Header definition
[sourcecode language="csharp"]
public class WSHeader: SoapHeader
{
public WSHeader()
{

}
private DateTime _CallTime;
public DateTime CallTime
{
get { return _CallTime; }
set { _CallTime = value; }
}
}
[/sourcecode]

Webservice difinition and header assignment
[sourcecode language="csharp"]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TimingService : System.Web.Services.WebService
{
public WSHeader DiscountHeader;
public TimingService()
{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
[SoapHeader("DiscountHeader", Direction = SoapHeaderDirection.In)]
public double Discount(DateTime birthdate)
{
if (DiscountHeader == null)
throw new SoapHeaderException("User invalid", SoapException.ClientFaultCode);
else if (birthdate > DateTime.Now)
{
throw new SoapException("Birthdate invalid", SoapException.ClientFaultCode);
}
else
{
if (DateTime.Now.Year - birthdate.Year < 18)
return 0.1;
else
return 0.0;
}
}
}
[/sourcecode]

Call method from client
[sourcecode language="csharp"]
namespace Client
{
class Program
{
static void Main(string[] args)
{
try
{
WS.WSHeader header = new Client.WS.WSHeader();
header.CallTime = DateTime.Now.AddDays(-1);

WS.TimingService client = new Client.WS.TimingService();

client.WSHeaderValue = header;

Console.WriteLine("Discount per: "+ client.Discount(new DateTime(2013, 1, 1))*100 + "%");
}
catch (SoapHeaderException ex)
{
Console.WriteLine("Header error: " + ex.Message);
}
catch(SoapException ex)
{
Console.WriteLine("Call error: " + ex.Message);
}
}
}
}
[/sourcecode]

No comments:

Post a Comment

Translate