title: How to catch forms authorization error in Web API in ASP.NET MVC4
body: <p>ASP.NET / Mono MVC4 Web API v.1 application.</p>
  
  <p>API controllers are using Forms authorication and are decorated with standard [Authorize]
  attribute.
  If authorization fails, standard  api error message </p>
  
  <pre><code>&lt;Error&gt;
  &lt;Message&gt;Authorization has been denied for this request.&lt;/Message&gt;
  &lt;/Error&gt;
  </code></pre>
  
  <p>occurs.
  How to itercept this error for sriting to log file .
  Error message returned to caller shoudl remain the same. 
  how to add additional code to this which can wrote this error message with whole http
  request headers and body to log file ?</p>
  
  <p>I added code from question</p>
  
  <p><a href="https://stackoverflow.com/questions/15167927/how-do-i-log-all-exceptions-globally-for-a-c-sharp-mvc4-webapi-app">How do I log ALL exceptions globally for a C# MVC4 WebAPI app?</a></p>
  
  <p>and from</p>
  
  <p><a href="https://stackoverflow.com/questions/20212725/how-to-catch-undefined-api-method-calls-in-asp-net-mvc4-web-api">How to catch undefined api method calls in ASP.NET MVC4 Web API</a></p>
  
  <p>but athorization error is not catched.</p>
  
  <p>How to catch all errors ?</p>
  
  <p><strong>Update</strong></p>
  
  <p>code needs to run in Windows 2003 server.
  I tried code from answer but got compile errors</p>
  
  <pre><code>Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported
  
  Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?
  
  Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?
  </code></pre>
  
  <p>How to run int in W2003 server ?</p>