How to implement custom fault codes with ASP.NET Web services (833381)
The information in this article applies to:
- Microsoft Web Services (included with the .NET Framework 1.1)
- Microsoft Web Services (included with the .NET Framework) 1.0
SUMMARYThis step-by-step article describes how to raise a custom
exception that exposes the method for
dividing two numbers in a Web service and how to create a console application that consumes the Web Service and handles the custom exception. back to the
topRequirementsThis
article assumes that you are familiar with the following topics:
- Programming with Microsoft ASP.NET 1.1 or with ASP.NET 1.0
- Handling exceptions in the Microsoft .NET Framework 1.1 or in the .NET Framework 1.0
The following list outlines the recommended hardware, software,
network infrastructure, and service packs that you need: - Microsoft Visual Studio .NET 2003 or Microsoft Visual
Studio .NET 2002
- Microsoft Internet Information Server 6.0 or Microsoft Internet
Information Server 5.0
- Microsoft 2003 .NET Server, Microsoft Windows XP, or Microsoft
Windows 2000 Server
back to the topHow to create a Web Service that raises a custom exception- Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.
- On the File menu, click
New, and then click Project.
- Under
Project types, click Visual C# Projects.
- Under Templates, click ASP.NET Web Service.
- Type http://ServerName/MathService in the Location box, and then click OK.
Note In this step, ServerName is a placeholder for the actual name of the server. - Add the following namespaces to the Server1.asmx.cs file:
using System.Web.Services.Protocols;
using System.Xml; - Flag each method that will be exposed from the service with
a WebMethod attribute.
Note You must define the methods to encapsulate the functionality of your
service. Without the WebMethod attribute, the methods will not be exposed from the service. However, every method does not have to use the WebMethod attribute. It might be
useful to hide some implementation details that are called by public Web service methods.
It might also be useful to hide some implementation details if the WebService class is also used in
local applications. A local application can use any public class, but only methods with the
WebMethod attribute can be accessed remotely as Web services. - Add the following methods to the Service1 class in the Service1.asmx.cs file:
[WebMethod]
public float Divide(int firstParameter, int secondParameter)
{
float result;
try
{
result = OperationDivision(firstParameter, secondParameter);
}
catch(InvalidParameterException ex)
{
throw RaiseException("http://tempuri.org/MathService","Divide",ex.Message,
"1000",ex.Source, "Client.InvalidInputParameter");
}
return result;
}
private float OperationDivision(int firstParameter, int secondParameter)
{
//Throw a custom exception if the second parameter is ZERO.
if (secondParameter == 0)
{
InvalidParameterException invalidParameter =
new InvalidParameterException("Second parameter passed from client to WebMethod [Divide] is ZERO (0).") ;
throw invalidParameter;
}
return (firstParameter / secondParameter);
}
private SoapException RaiseException(string uri, string webServiceNamespace,
string errorMessage, string errorNumber, string errorSource, string specificFaultCode)
{
XmlQualifiedName faultCodeLocation = null;
//Create fault code that is specific to the Application exception.
faultCodeLocation = new XmlQualifiedName(specificFaultCode, "http://schemas.xmlsoap.org/soap/envelope/");
XmlDocument xmlDoc = new XmlDocument();
//Create the Detail node.
XmlNode rootNode = xmlDoc.CreateNode(XmlNodeType.Element, SoapException.DetailElementName.Name, SoapException.DetailElementName.Namespace);
//Build specific details for the SoapException.
//Add the first child of the detail XML element.
XmlNode errorNode = xmlDoc.CreateNode(XmlNodeType.Element,"Error", uri);
//Create and then set the value for the ErrorNumber node.
XmlNode errorNumberNode = xmlDoc.CreateNode(XmlNodeType.Element,"ErrorNumber", uri );
errorNumberNode.InnerText = errorNumber;
//Create and then set the value for the ErrorMessage node.
XmlNode errorMessageNode = xmlDoc.CreateNode(XmlNodeType.Element,
"ErrorMessage", uri );
errorMessageNode.InnerText = errorMessage;
//Create and then set the value for the ErrorSource node.
XmlNode errorSourceNode = xmlDoc.CreateNode(XmlNodeType.Element,"ErrorSource", uri);
errorSourceNode.InnerText = errorSource;
//Append the Error child element nodes to the root detail node.
errorNode.AppendChild(errorNumberNode);
errorNode.AppendChild(errorMessageNode);
errorNode.AppendChild(errorSourceNode);
//Append the Detail node to the root node.
rootNode.AppendChild(errorNode);
//Construct the exception.
SoapException soapEx = new SoapException(errorMessage, faultCodeLocation, uri, rootNode);
//Raise the exception back to the caller.
return soapEx;
}
- Add the following class to the "MathService" namespace:
public class InvalidParameterException: ArgumentException
{
public InvalidParameterException()
{
}
public InvalidParameterException(string message)
: base(message)
{
}
public InvalidParameterException(string message, Exception inner)
: base(message, inner)
{
}
} - On the Build
menu, click Build Solution to build the Web service.
back to the topHow to create a console application that consumes the Web Service and handles the custom exception- Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.
- Under Project types, click Visual
C# Projects.
- Under Templates, click Console Application, and then click OK.
- Add a Web reference to the "MathService" Web service that you created in the "Create a Web Service that raises a custom exception" section as follows.
Note In this step, you create a proxy class on the client
computer. After the proxy class is created, you can create objects based on the
proxy class. Typically, each method call that is made by using these objects goes to the
uniform resource identifier (URI) of the Web service as a SOAP
request.- On the Project menu, click Add
Web Reference.
- In the Add Web Reference dialog box,
type the URL for the Web service in the URL text box, and
then click Add Reference.
Note If you set the local computer to host the Web service, type the following URL in the URL text box: http://localhost/MathService/Service1.asmx
- Add the following code at the top:
using System.Web.Services.Protocols;
using System.Xml; - Add the following code to the Main method to create an instance of the proxy object:
localhost.Service1 myMathService = new localhost.Service1(); - Add the following code to the Main method to invoke a method on the proxy object that you created in step 5:
try
{
Console.WriteLine("6 / 0 = {0}",myMathService.Divide(6, 0));
}
catch (SoapException soapEx)
{
//Load the Detail element of the SoapException object.
XmlDocument doc = new XmlDocument();
doc.LoadXml(soapEx.Detail.OuterXml);
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
//Add the namespace to the NamespaceManager.
nsManager.AddNamespace("errorNS", "http://tempuri.org/MathService");
XmlNode categoryNode = doc.DocumentElement.SelectSingleNode("errorNS:Error",nsManager);
string errorNumber = categoryNode.SelectSingleNode("errorNS:ErrorNumber",nsManager).InnerText;
string errorMessage = categoryNode.SelectSingleNode("errorNS:ErrorMessage",nsManager).InnerText;
string errorSource = categoryNode.SelectSingleNode("errorNS:ErrorSource",nsManager).InnerText;
Console.WriteLine("Error occured in the Web Service ");
Console.WriteLine("Error Number : " + errorNumber);
Console.WriteLine("Error Message : " + errorMessage);
Console.WriteLine("Error Source : " + errorSource);
//Custom fault code that is created at the WebService is accessible in the client application.
//By using this custom fault code, this error message, and this error number,
//the client application can receive a type of exception thrown in WebService.
Console.WriteLine("Fault code specific to Application Exception : "+soapEx.Code.Name.ToString());
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
} - On the Build menu, click Build Solution.
- On the Debug
menu, click Start to test the application.
back to the
topREFERENCESFor more information, visit the following Microsoft
Developer Network (MSDN) Web site: back to the
top
Modification Type: | Major | Last Reviewed: | 8/3/2004 |
---|
Keywords: | kbHOWTOmaster kbWebServices kbExceptHandling kbhowto KB833381 kbAudDeveloper |
---|
|
|
©2004 Microsoft Corporation. All rights reserved.
|
|