title: Setting the response error in authentication handler
body: <p>I'm writing a Web API in using the MVC 4 Web API framework. I'm using <code>BASIC</code> authentication with a custom authentication message handler inheriting from <code>DelegatingHandler</code>.</p>
  
  <p>Everything is working peachy, except my error handling.</p>
  
  <p>I'm using the Web API as a wrapper over an existing authentication mechanism and an exception is thrown when the user's password is expired. Within the API action methods, I am able to handle this easily by throwing an HTTPResponseException and I get a tidy little json object such as below:</p>
  
  <pre><code>{
  "Message": "Password is expired."
  }
  </code></pre>
  
  <p>If I try this same approach in my Auth Message Handler, I get all the nasty .NET response output.</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.&lt;/title&gt;
      &lt;style&gt;
       body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
       p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
  ... you get the idea ...
  </code></pre>
  
  <p>I think I'm close... in <code>SendAsync</code>  </p>
  
  <pre><code>catch (Exception ex)
  {
      var response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
      response.Headers.Add("WWW-Authenticate", "Basic realm=\"myrealm\"");
  }
  </code></pre>
  
  <p>Here, perhaps if I can somehow get a <code>Task&lt;HttpResponseMessage&gt;</code> from my response object to return, I think I might be ok.</p>
  
  <p>Basically my question is "How should exception handling really be done so that I am able to return a nice json/xml object to the user?"</p>
  
  <p>One more thing to note, this is .NET 4, not 4.5. I've seen a few examples using the <code>await</code> keyword, but that won't work in this scenario.</p>