WCF Web API

There is a new API for doing REST with WCF: WCF Web API http://wcf.codeplex.com

Here is a quick getting started blog:

1] Create a new empty ASP.NET application

image

2] Add WebApi.All from NuGet

image

3] Add new class

using System.ServiceModel;

using System.ServiceModel.Web;

 

namespace WcfWebApi

{

    public class Contact

    {

        public int Id { get; set; }

        public string Name { get; set; }

    }

 

    [ServiceContract]

    public class ContactService

    {

        [WebGet(UriTemplate="")]

        public Contact Get()

        {

            return new Contact() { Name = "Bert", Id = 999 };

        }

    }

}

4] Add global.asax file and add a route ‘contact’

using System;

using System.Web.Routing;

using Microsoft.ApplicationServer.Http.Activation;

 

namespace WcfWebApi

{

    public class Global : System.Web.HttpApplication

    {

        protected void Application_Start(object sender, EventArgs e)

        {

            RouteTable.Routes.MapServiceRoute<ContactService>("contact");

        }

    }

}

To get this code running I needed to add a reference to Microsoft.ApplicationServer.HttpEnhancements.dll and namespace ‘Microsoft.ApplicationServer.Http.Activation’

5] Run in browser ‘/contact’ to get XML back

image

6] Run in Fiddler with ‘accept:application/json’ in the header to get JSON back

image 

Conclusion: with just a bit of code we can quickly create REST services that return XML/JSON format. No hassle with cryptic XML config files anymore Smile

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s