Monday, 31 December 2018

Removing the JSON or XML Formatter in WEB API

You can remove the JSON formatter or the XML formatter from the list of formatters, if you do not want to use them. The main reasons to do this are:

·       To restrict your web API responses to a particular media type. For example, you might decide to support only JSON responses, and remove the XML formatter.
·       To replace the default formatter with a custom formatter. For example, you could replace the JSON formatter with your own custom implementation of a JSON formatter.

The following code shows how to remove the default formatters. Call this from your Application_Start method, defined in Global.asax.

void ConfigureApi(HttpConfiguration config)
{
    // Remove the JSON formatter
    config.Formatters.Remove(config.Formatters.JsonFormatter);

    // or

    // Remove the XML formatter
    config.Formatters.Remove(config.Formatters.XmlFormatter);

}

No comments:

Post a Comment