6

Is there a C# or .NET class to handle HTTP Content Negotiation with a User Agent?

I would like to be able to supply a list of acceptable Content Types, and have those negotiated with the browser to find the best match.

Jamie
  • 71
  • 3
  • I don't understand your question. Can you elaborate? – Sky Sanders May 22 '10 at 14:48
  • http://en.wikipedia.org/wiki/Content_negotiation Content Negotiation is part of the HTTP Specification that allows a User Agent (browser) to list the media types it will accept a document in order of "quality". So in my code I would like to pass in the formats I can generate, and have the class apply the Content Negotiation rules as defined in the Specification and return me the best media type to send back. – Jamie May 22 '10 at 14:52
  • If my application can render a piece of data in either HTML, XHTML, XML, PDF or JSON. I need to know which the browser supports, and specifically which one it considers the best quality. – Jamie May 22 '10 at 14:58

2 Answers2

1

I recently wrote a content negotiation library in F#.

I blogged about it here.

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275
0

I think the word user agent is a bit off in your question but if you want to build request a certain source (lets say a restfull api). You can use the WCF Rest Starter kit (http://wcf.codeplex.com/) to specify the type of content you want or accept:

HttpClient client = new HttpClient(new Uri("http://restfull/api/"));
//this is XML but could be JSON or whatever the API can supply
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var response = client.Get(path);

if (response != null)
{
  response.EnsureSuccessStatusCode();
  //this will be XML
  string xml = response.Content.ReadAsString();
}
Didier Caron
  • 570
  • 3
  • 9
  • This is client-side code, the OP is asking about server-side code. Also, content negotiation in WCF is currently broken: http://wcf.codeplex.com/workitem/40 – Mauricio Scheffer Jun 10 '11 at 04:45