title: Different return types for ASP.NET Web API
body: <p>I am attempting to write truly RESTful web services over HTTP using ASP.NET MVC 4 Web API.</p>
  
  <p>The current challenge I have is to return different return types (entity-body) based upon my status code.</p>
  
  <p>For example, for resource Hammer I have a .NET model class "Hammer", and a HammerController:</p>
  
  <pre><code>namespace Awesomeness
  {
      public class HammerController : ApiController
      {
          public Hammer Get(int id)
          {
          }
  ...
  </code></pre>
  
  <p>If the ID doesn't exist (404) or requires different authorization (401), I can easily shortcut the return and manually set the status code and any other content, which is cool.  However, in many non-2xx statuses, I want to return a different entity-body than the Hammer resource representation.  I can easily do this manually, but I'd like to take advantage of the ASP.NET MVC 4 Web API automagic serialization and deserialization to/from XML or JSON depending on the request headers.</p>
  
  <p><strong>So my core question is:  Can I take advantage of ASP.NET MVC 4 Web API's automagic serialization while returning differing return types?</strong></p>
  
  <p>Some potential approaches I have thought about are:</p>
  
  <ol>
  <li><p>Have the controller method return the main resource type, but short-circuit the return with <code>HttpContext.Current.Response</code> and somehow hook into the automagic serialization (preferred).</p></li>
  <li><p>Have my Model class be more like a C union where it represents this type or that type and let it get serialized as part of the normal return process (and just override status code and any response headers needed).  Even if I think through how to do this, I have a feeling it would still end up being very hacky.</p></li>
  </ol>
  
  <p><strong>Edited Apr 27 2012:</strong>  I can throw an HttpResponseException like this:</p>
  
  <pre><code>HttpResponseMessage response = new HttpResponseMessage(statusCode);
  if (!string.IsNullOrWhiteSpace(text))
  {
      response.Content = new StringContent(text);
  }
  throw new HttpResponseException(response);
  </code></pre>
  
  <p>...but now I need to figure out how to hook into the auto-magic serialization and set the <code>response.Content</code> to the <code>Accept</code> header negotiated representation.</p>