Skip to content

Instantly share code, notes, and snippets.

@darrelmiller
Created January 21, 2012 21:31
Show Gist options
  • Save darrelmiller/1654104 to your computer and use it in GitHub Desktop.
Save darrelmiller/1654104 to your computer and use it in GitHub Desktop.
public static class FormatterCollectionExtensions
{
public static Tuple<MediaTypeFormatter,MediaTypeHeaderValue> Negotiate<T>(this MediaTypeFormatterCollection formatters, HttpRequestMessage requestMessage)
{
var formatSelector = new FormatterSelector();
MediaTypeHeaderValue mediaType = null;
var response = new HttpResponseMessage() {RequestMessage = requestMessage};
var formatter = formatSelector.SelectWriteFormatter(typeof(T), new FormatterContext(response, false), formatters, out mediaType);
return new Tuple<MediaTypeFormatter, MediaTypeHeaderValue>(formatter,mediaType);
}
}
public HttpResponseMessage Get() {
var response = new HttpResponseMessage();
var contact = new Contact() {FirstName = "Joe", LastName = "Brown"};
var mediaInfo = Configuration.Formatters.Negotiate<Contact>(Request);
response.Content = new SimpleObjectContent<Contact>(contact, mediaInfo.Item1);
response.Content.Headers.ContentType = mediaInfo.Item2;
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment