JsonMediaTypeFormatter's Supported Media Types

Topics: Web Api
Apr 22, 2011 at 9:32 PM

Hey guys,

I have a method following an example in the latest ACS bits from acs.codeplex.com that retrieves a simple web token from ACS:

	private static string GetTokenFromAcsOAuth2_13()
		using (var httpClient = new HttpClient(AccessControlServiceConfiguration.BaseUri.Production))
			var values = new[]
				             	new KeyValuePair<string, string>("grant_type", "client_credentials"),
				             	new KeyValuePair<string, string>("client_id", AccessControlServiceConfiguration.ClientId.Production),
				             	new KeyValuePair<string, string>("client_secret", AccessControlServiceConfiguration.ClientSecret.Production),
				             	new KeyValuePair<string, string>("scope", "http://localhost:9000/")
			var content = new FormUrlEncodedContent(values);

			using (HttpResponseMessage httpResponseMessage = httpClient.Post("v2/OAuth2-13", content))
				//var dataContractJsonSerializer = new DataContractJsonSerializer(typeof(OAuth2TokenResponse));
				//var tokenResponse = (OAuth2TokenResponse)dataContractJsonSerializer.ReadObject(httpResponseMessage.Content.ContentReadStream);
				//return tokenResponse.access_token;

				return httpResponseMessage.Content.ReadAsJson<OAuth2TokenResponse>().access_token;

I created an extension method for a convenient way to serialize HttpContent to JSON:

	public static class HttpContentExtensions
		private static readonly JsonMediaTypeFormatter jsonMediaTypeFormatter = new JsonMediaTypeFormatter();

		public static T ReadAsJson<T>(this HttpContent content)
			return content.ReadAs<T>(new[] { jsonMediaTypeFormatter });

Unfortunately, this method results in the following exceptions:

	System.InvalidOperationException was unhandled by user code
  Message=No 'MediaTypeFormatter' is available to read an object of type 'OAuth2TokenResponse' with the media type 'application/json'.

I traced the problem down to MediaTypeFormatter.TryMatchSupportedMediaType and the issue is that JsonMediaTypeFormatter's supported media type for "application/json" specifies a charset of "utf-8" and the result from ACS is returned as "application/json; charset=us-ascii".  Since the charsets don't match, the response is not serialized.

So, can JsonMediaTypeFormatter be updated to include that media type/charset combo?  If not, I guess I will go back to the old way of doing things that works.  I don't think writing a custom formatter is the way to go here.  Also, I think it would be nice if you guys updated the exception text to indicate the charset since that's where the equality failure occurred.  I was originally thrown off by the exception text because the media types were identical.

Thanks for your consideration and feedback.