title: How do I get Web API 2 to return JSON and no other content type?
body: <p>In the latest Web API 2, how do I configure it so that it will only return a reply if the <code>Accept</code> header is <code>application/json</code>?  This API will only support json, if any other accept header is sent then an error must be thrown.  There will be no xml and even no html interface.  </p>
  
  <p>If the client asks for xml or html or anything, we need to throw an error to let them know they used the wrong accept type.  We must not mask this problem by replying with the correct json when they have requested a type that is not actually supported.</p>
  
  <pre><code>var request = (HttpWebRequest)WebRequest.Create(url);
  request.Accept = "application/json";
  var response = request.GetResponse();
  </code></pre>
  
  <p>And the json result is returned successfully. But if there is any other <code>Accept</code> then an error is returned</p>
  
  <pre><code>var request = (HttpWebRequest)WebRequest.Create(url);
  request.Accept = "application/xml"; // or text/html or text/plain or anything
  var response = request.GetResponse();
  </code></pre>
  
  <p>Returns <code>HTTP 501 Not Implemented</code> or similar http error code.</p>
  
  <p>This question is not a duplicate of <a href="https://stackoverflow.com/q/9847564/325727">How do I get ASP.NET Web API to return JSON instead of XML using Chrome?</a> - that question asks how to <em>also</em> return json. My question is how to <em>only</em> return json, and only if the client asks for json.  If the client asks for any other type like xml or html, then an error is returned.</p>