Returns custom HTTP code from ActionFilterAttribute

I am using the following code to throttle 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 am unable to return error code 429 because it is not in the HttpStatusCode enumeration. Is there a way to return a custom error code?

+5


source to share


3 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 it helps

+7


source


This is what I did based on another answer on StackOverflow.

Create class (in controller file worked for me)

    public class TooManyRequests : IHttpActionResult
    {

    public TooManyRequests()
    {       
    }

    public TooManyRequests(string message)
    {
         Message = message;
    }
    public string Message { get; private set; }

    public HttpResponseMessage Execute()
    {
        HttpResponseMessage response = new HttpResponseMessage((HttpStatusCode)429);
        if (!string.IsNullOrEmpty(Message))
            {
            response.Content = new StringContent(Message); // Put the message in the response body (text/plain content).
        }
        return response;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }
}

      



Use in controller

public IHttpActionResult Get()

{        
    // with message
    return  new TooManyRequests("Limited to 5 request per day. Come back tomorrow."); 

    // without message 
    // return  new TooManyRequests(); 

}

      

0


source


Assuming you ActionFilterAttribute

need to create your own code based on the status code, you can write like this:

        if (necessity_to_send_custom_code)
        {
            actionContext.Response = actionContext.Request.CreateResponse((HttpStatusCode)855, "This is custom error message for you");
        }

      

Hope this helps.

0


source







All Articles