Home > ASP.NET Web API, C#, REST > Changing the supported media types of the default media formatters in the ASP.NET Web API client library

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);
Advertisements
Categories: ASP.NET Web API, C#, REST
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: