Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return custom HTTP code from ActionFilterAttribute

I use the code below to throttle my ASP.NET Web Api:

public class Throttle : ActionFilterAttribute
{
    public override async Task OnActionExecutingAsync(HttpActionContext context, CancellationToken cancellationToken)
    {
            // ...
            if (throttle)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict));
            }
    }
}

However, I cannot return error code 429, because it's not in HttpStatusCode enum. Is there a way to return a custom error code?

like image 257
user1613797 Avatar asked Aug 15 '14 10:08

user1613797


1 Answers

I found this over here.

var response = new HttpResponseMessage
  {
     StatusCode = (HttpStatusCode)429,
     ReasonPhrase = "Too Many Requests",
     Content = new StringContent(string.Format(CultureInfo.InvariantCulture, "Rate                       limit reached. Reset in {0} seconds.", data.ResetSeconds))
  };

    response.Headers.Add("Retry-After", data.ResetSeconds.ToString(CultureInfo.InvariantCulture));
    actionContext.Response = response;

Hope this helps

like image 90
satish Avatar answered Oct 15 '22 03:10

satish