In ASP.Net Web API, how to change the default formatting for a specific controller or action

We have a web API site that will be used for several purposes:

  • In developing clients, such as the iPhone application we are creating, it will consume JSON in the first place.
  • From regular users via RSS clients who add it to their favorite RSS reader (e.g. Flipboard).

I created a custom RSS 2.0 based on this link and configured it in WebApiConfig

public static void Register(HttpConfiguration config) { config.Formatters.Add(new SyndicationMediaTypeFormatter()); 

It accepts both receiving headers for the application / rss + xml and application / atom + xml.

Users usually embed RSS feeds into their rss clients without knowing anything about the headers, so I need some sort of RSS feeds by default.

However, this is a brown field development, and json feeds are already in use, currently the default, and I cannot change the default formatter on the entire site without adversely affecting existing developer clients.

Can I make this the default formatting for a specific controller, but not for the site as a whole?

+6
source share
1 answer

You can use IControllerConfiguration to determine the configuration of each controller.

This is the pattern that describes this scenario. You can take a quick look at how this interface should be used in here (from an example).

Custom configuration example:

 public class CustomControllerConfigAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { // Register an additional plain text media type formatter controllerSettings.Formatters.Add(new PlainTextBufferedFormatter()); } } 

Source PlainTextBufferedFormatter if you're interested.

+7
source

All Articles