Many RESTful web services allow the User Agent to dictate which representation it requires through an alternative mechanism to the Accept header. Typically this is by changing the URL in some way.
The ROM assembly supports this through a query string parameter. To start using this feature you will need to replace the MapRoute set of extension methods typically used in ASP.Net MVC with the MapRomRoute extensions provided by the ROM assembly. By changing from:
it is possible to use a browser to call the web service and force different representations:
- http://localhost/Products will return the XHTML representation
- http://localhost/Products?format=xml will return the XML representation
- http://localhost/Products?format=json will return the JSON representation
The sample project uses the MapRomRoute extension in the the Application_Start method in Global.asax. The extensions can also be used in the Area Registration classes if your web service is going to use Areas.
If you don’t like the to use “format” as the name of the query string parameter, you can change it by setting the following property on application start up (i.e. in the Application_Start method again):
RestfulHttpRequestWrapper.ContentTypeQueryStringId = "rep";
What is it Doing?
If you are interested how this is working, it was explained in an earlier post. Essentially it makes use of a custom HttpRequestWrapper which overrides the AcceptTypes property. However, since this cannot be injected directly, a custom HttpContextWrapper is used… which can only be introduced by a custom MvcHandler… which needs to be added as a route is registered, hence the custom version of the MapRoute extension!
The MultipleRepresentations action filter, that was introduced in the Bare Minimum Part 1 post, uses the AcceptTypes property to decide which Format Handler should be used to render the response. By default these are:
- XhtmlFormatHandler – this handles any “text/html”, “application/xhtml+xml” or “*/*” requests and uses the ASP.Net MVC Framework’s standard view mechanism. It will also handle requests with an AcceptTypes set to the more friendly name off “xhtml” or “help” (which is described in a later post.
- XmlFormatHandler – this handles any “text/xml” or “application/xml” requests and uses the the .Net Framework’s XmlSerializer (meaning any of the XmlSerializer attributes can be used on the model classes to change the format of the Xml generated). It will also handle requests with an AcceptTypes set to the more friendly name off “xml”.
It is possible to change the format handlers used by registering a different set at start up. This will be covered in a later post. For example, the ROM assembly comes with a handler that uses the Json.Net assembly which allows greater control over the Json generated than does the JsonScriptSerializer.
The sample is available here: Samples.WebService.zip (4.39 mb)
The next few blogs will explain more of the features the ROM assembly will support.