In ASP.Net Web API, how do you change the default formatter for specific Controller or Action

StackOverflow https://stackoverflow.com/questions/22464772

Вопрос

We have a Web API site running and it's going to be used for multiple purposes:

  1. In development clients, such as an iPhone app that we build, that will primarily consume JSON.
  2. By normal users through RSS clients, who will 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 accept headers for application/rss+xml and application/atom+xml.

Users typically paste RSS feeds into their rss clients without knowing anything about headers -- so I need to have some routes that are RSS by default.

However, this is brownfield development and the json feeds are already in use, currently as the default, and I cannot change the default formatter throughout the site without adversely affecting existing developer clients.

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

Это было полезно?

Решение

You can use IControllerConfiguration to define per-controller specific configuration..

This is a sample which describes this scenario. You can quickly take a look at how this interface should be used over here(from the sample).

An example of a custom configuration is:

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());
    }
}

The source for PlainTextBufferedFormatter if you're curious.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top