title: Returning "429 Too Many Requests" from action attribute
body: <p>I'm writing a class which I can use as an attribute on my ASP.NET Web API actions which will rate limit users based on their IP address.</p>
  
  <p>The logic of the class works fine, and its basic structure looks like:</p>
  
  <pre><code>public class ThrottleAttribute : ActionFilterAttribute
  {
  
      public override void OnActionExecuting(HttpActionContext actionContext)
      {
          // Do various logic to determine if we should respond with a 429
  
          base.OnActionExecuting(actionContext);
      }
  }
  </code></pre>
  
  <p>And I'm using it on my controller actions by adding the <code>[Throttle]</code> annotation above the method definition.</p>
  
  <p>Somewhere in the <code>OnActionExecuting</code> method I want to return a response with the <code>429</code> HTTP code. From looking at other SO posts (<a href="https://stackoverflow.com/questions/20817300/how-to-throttle-requests-in-a-web-api">this one</a> for example) it seems I can do that with something like the following:</p>
  
  <pre><code>actionContext.Response = actionContext.Request.CreateResponse(
              HttpStatusCode.Conflict, 
              Message.Replace("{n}", Seconds.ToString())
          );
  </code></pre>
  
  <p>When I try to use this code I get the following error:</p>
  
  <blockquote>
    <p>'System.Net.Http.HttpRequestMessage' does not contain a definition for 'CreateResponse' and no extension method 'CreateResponse' accepting a first argument of type 'System.Net.Http.HttpRequestMessage' could be found (are you missing a using directive or an assembly reference?)</p>
  </blockquote>
  
  <p>Obviously, the <code>CreateResponse</code> method doesn't exist on <code>HttpRequestMessage</code>, but I don't know how else to return a custom response to tell the user they've hit their rate limit. I also tried this:</p>
  
  <pre><code>actionContext.Response.StatusCode = HttpStatusCode.BadRequest;
  </code></pre>
  
  <p>But that also resulted in an error about an Object reference not being set to an instance of an object.</p>
  
  <p>How do I return a <code>429 Too Many Requests</code> response from my class, or failing that, just a <code>Bad Request</code> response?</p>