Tuesday, February 13, 2007

Dynamic ASP.NET web service proxy generation

For many times I have been annoyed by the automatic proxy generation of the ASP.NET web services in Visual Studio. I wanted to work in a more “WCF” style (Windows Communication Foundation), as in using “operation contracts” and “data contracts”. Unfortunatelly, there was no way of doing this in asp.net web services. You had to deal with the duplicated code done by the generator, or you had to manually modify and update the proxy. I considered developing a library for dynamic generation of the web service using only the service contract and the address of the service. With WCF, the asp.net web services are somehow obsolete, but I thought it wouldn’t be so bad to publish my solution, since I havent’ found any way to do dynamic web proxy generation.

Here is how you should use the web service:

  1. First, write the service contract (the web service interface, and the data transfer

    objects). Example:

    public interface IWebServiceInterface
    string HelloWorld();
    int GetSum(int a, int b);
    UserDetails GetDetails(string firstName,string lastName,int age);

  2. Then write the service implementation using ASP.NET web services:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    public class Service : System.Web.Services.WebService, IWebServiceInterface

    #region IWebServiceInterface Members

    public string HelloWorld()
    return "Hello World";

    public int GetSum(int a, int b)
    return a + b;
    public UserDetails GetDetails(string firstName, string lastName, int age)
    UserDetails ret= new UserDetails(firstName,lastName,age);
    return ret;


Publish the web service, and in order to use it, create a IWebServiceInterface instance:

IWebServiceInterface dynamicService =

And there you have it – the dynamic generated asp.net web proxy. You don’t have to worry about duplicated code or manual updates anymore. But pay attention, if you intend to use this code, you shouln’t modify the method or the types namespaces, or other details provided by the attributes, because the library uses only the contract to generate the proxy, and not the information from the WSDL. So the proxy presumes that the web service is in the "http://tempuri.org/" namespace, and all methods are decorated with the [WebMethod] attribute, with no parameters, just as they are generated by the visual studio IDE.

The code generation is done using the System.CodeDom namespace. If you have questions don’t hesitate to write me, or post a comment.

Download source code