Resources Over MVC - Bare Minimum Part 2

October 31, 2011 21:29 by Admin

Bare Minimum Part 1 of this series showed how to add a read only web service to an ASP.Net MVC web site with one line of code. In this post we’ll add a second line of code to give us a web service that can receive data.

Receiving Multiple Representations

Just as we want to be able to serve multiple representations of the same resource, we would also like to receive multiple representations. To add this capability to your web service you can use a Custom Model Binder that comes as part of the ROM assembly. There are two options for introducing the MultipleRepresentationsBinder:

  • Use the [MultipleRepresentationsBinder] attribute on any action parameters that should be bound to the request body e.g.:
         public ActionResult Index([MultipleRepresentationsBinder] Product newProduct)

  • Register it as the default model binder for the entire web site. You do this by using the following in the Application_Start method in Global.asax:
         ModelBinders.Binders.DefaultBinder = (new MultipleRepresentationsBinder());


So now your existing web site, into which you want to incorporated a simple web service, that can accept PUT and POST of data in different formats by adding a single attribute!

Trying it Out

Below is a link to a sample project that contains an ordinary ASP.Net MVC web site (straight out of the box). The following changes have been made:

  • An area called Services has been added
  • Product and ProductCollection classes have been added to the area’s Model
  • Within the Services area is a ProductController which will serve a ProductCollection or an individual Product . It will also accept a POST of a new or PUT of a new/existing Product.
  • The main page of the web site has a few buttons added, behind which are client side JavaScript functions that interact with the web service (using either XML or JSON) from the user’s browser.

This simple sample uses the [MultipleRepresentations] and [MultipleRepresentations] attributes only with the ProductController, which allows the rest of the web site to function as normal.

Download the sample: (4.49 mb)

Note: This is a very rough and ready sample that performs few checks on the data passed in!

What’s Next

The next post will start a web site from scratch.

Add comment

  Country flag

  • Comment
  • Preview