This series of posts is introducing the features in the ROM code. If you haven’t been there already, take a look at the introduction and perhaps download the source from CodePlex. The absolute minimum you need to get going with Resources Over MVC (ROM) is an existing ASP.Net MVC web site, a reference to the ROM assembly (via NuGet) and a single line of code.
Serving Multiple Representations
- Add a reference to the Resources Over MVC assembly to the project (you can do this through NuGet or download it from CodePlex).
- Hook up ROM’s Rest Enabled action filter by either:
- Adding a [MultipleRepresentations] attribute to each action you want to support multiple representations or
- Adding a [MultipleRepresentations] attribute to each Controller you want to support multiple representations on all its Actions or
- Adding it as a global filter on Application start-up so that all Actions in all Controllers support multiple representations. You do this by using the following in the Application_Start method in Global.asax:
So if you have an existing web site, into which you want to incorporate a simple web service, that can serve read only data in different formats, create a new Controller and add the [MultipleRepresentations] attribute to it. That is all!
Trying it Out
Now, if a User Agent sends a request having set an Accept header such as:
GET http://mymachine/services/products/ HTTP/1.0
The web service will return:
HTTP/1.1 200 OK
Content-Type: application/xml; charset=utf-8
Date: Thu, 02 Jun 2011 20:01:29 GMT
<?xml version="1.0" encoding="utf-8"?>
You can try this using a tool such as Fiddler which allows you to ask for different representations.
Note: If you do use Fiddler, you will need to ensure your project is set up to use your local IIS Web Server rather than the Visual Studio Development Server (right click the project, select Properties… then go to the Web tab). Then in Fiddler use the Request Builder to perform a GET against the web service (using the machine name rather than localhost in the URI) with an Accept header set to “application/xml”.
If you try setting the Accept Header to “application/json” and you will get this response:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Thu, 02 Jun 2011 20:14:03 GMT
Note: In the above samples the server has provided a response using the default UTF-8 encoding. The actual encoding of the response can be set by the User Agent via the Accept-Charset header. The processing of both the Accept and Accept-Charset headers support the quality factor parameter.
The next post (Bare Minimum Part 2) will show how you can have your web service receive data in different formats… again by adding a single line of code. It will also include a downloadable sample project. Future posts will build a web service from scratch and introduce other features of the assembly.