0

In the creation of our new MVC Web API-based service, we want to focus on XML to begin with and add JSON functionality later as an enhancement, using the full release with native JSON.NET support. To that end, we want to prevent the service accepting requests or giving responses in JSON to avoid establishing any functionality we are expecting to break.

Is there a way to disable JSON support in the ASP.NET MVC API?

2 Answers 2

4

All you have to do is to remove JSON media formatters.

// Identify JSON formatters in global config.
var jsonMediaTypeFormatters = GlobalConfiguration.Configuration.Formatters
    .Where(x => x.SupportedMediaTypes
    .Any(y => y.MediaType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase)))
    .ToList();

// Remove formatters from global config.
foreach (var formatter in jsonMediaTypeFormatters)
{
    GlobalConfiguration.Configuration.Formatters.Remove(formatter);
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's the solution I expected. It would be great to see some code on how to do this.
@ProgrammingHero there you go. Updated.
where can I find the GlobalConfiguration object?
1

There's an even shorter option, because there can be only one Json formatter and the MediaTypeFormatterCollection exposes it as a property. Available since Web API 2 (maybe also in v1, not sure).

GlobalConfiguration.Configuration.Formatters.Remove(controllerSettings.Formatters.JsonFormatter)

1 Comment

where does this code go to? there is no Formatters property in my Startup class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.