REST in ASP.NET

SOAP based web services became too complicated (I completely agree), so Roy Fielding’s REST services emerged as the light-weight, quick and simple alternative. So I thought I would add some RESTful services to an ASP.NET project I’m working on. A quick scan around the internet revealed that this is no simple thing:

http://www.west-wind.com/weblog/posts/310747.aspx

http://msdn.microsoft.com/en-us/netframework/dd547388.aspx

Downloading a toolkit, setting up WCF Data and Service Contracts, messing about with web.config, blah blah, this is all too complicated, and is at complete odds with the REST principal of simplicity. So my solution? Create an ASP.NET page, remove everything on it, but a single repeater:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Rest.aspx.cs" Inherits="StateMagic.Web.Rest" %>
<?xml version="1.0"?><asp:Repeater runat="server" ID="repeater">
<HeaderTemplate><states>
</HeaderTemplate>
<ItemTemplate>  <state href="?state=<%#(Container.DataItem as string)%>&username=<%= Server.UrlEncode(this.Credentials.Username) %>&apikey=<%= this.Credentials.ApiKey %>&modelid=<%= this.ModelId%>"><%#(Container.DataItem as string)%></state>
</ItemTemplate>
<FooterTemplate></states>
</FooterTemplate>
</asp:Repeater>

Then in the code behind, you read in the parameters on the query string, perform the necessary database query, and bind the resulting objects to the repeater.

Yes, it’s ugly, but it’s simple, and you have ultimate control over the way the XML looks.

Perhaps it would be better to define an object model, and use the serializer to write that out to the response stream instead, but it seemed like more worker, and the serializer isn’t quick.

Advertisements