Cook Computing

XML-RPC Web Handler

April 7, 2003 Written by Charles Cook

I should have spotted this one before. How do you build an IIS XML-RPC service without compiling any code and without messing around with config files? Simple, use a web handler file. Create a file with a .ashx extension, like the example below, and put the XML-RPC.NET assembly in a bin directory underneath where the .ashx file lives (or put it in the GAC). Then point your XML-RPC client at the URL for the .ashx file.


<!- file: MathService.ashx ->
<%@ WebHandler Language="C#" Class="MathService" %>
 
<%@ Assembly Name="CookComputing.XmlRpc" %>
 
using System;
using System.Web;
using CookComputing.XmlRpc;
 
public class MathService: XmlRpcService
{
    [XmlRpcMethod("math.Add")]
    public int Add(int A,int B)
    {
      return A + B;
    }
 
    [XmlRpcMethod("math.Subtract")]
    public int Subtract(int A, int B)
    {
      return A - B;
    }
 
    [XmlRpcMethod("math.Multiply")]
    public int Multiply(int A, int B)
    {
      return A * B;
    }
 
    [XmlRpcMethod("math.Divide")]
    public int Divide(int A, int B)
    {
      if (B == 0)
      {
        throw new XmlRpcFaultException(1001, "Divide by zero");
      }
      return A/B;
    }
}

Deriving the WebHandler class, MathService in this example, from XmlRpcService supplies the necessary implementation of the ProcessRequest and IsReusable methods of the IHttpHandler interface. The implementation of ProcessRequest then uses reflection to map incoming XML-RPC requests to the methods marked with the XmlRpcMethod attribute.