Over a million developers have joined DZone.

Changing the Supported Media Types of the Default Media Formatters in the ASP.NET Web API Client Library

·

A couple of days ago, I encountered an issue when calling a REST service. The REST service was returning JSON data, but the content type in the HTTP header was set to “text/javascript”. This caused the default JSON formatter of the ASP.NET Web API client not to recognize the data (he expects “application/json”). It took me a while to find this proper solution as I wanted to avoid creating a custom formatter, but the ASP.NET Web API client library allows to modify the supported content types for the default content formatters.

HttpClient client = new HttpClient();

MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection();
formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));

HttpResponseMessage response = await client.GetAsync(url);
SearchResult result = await response.Content.ReadAsAsync(formatters);
Topics:

Published at DZone with permission of Pieter De Rycke, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}