Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roughconsensusandrunningcode/7c206092760ce07ebc12094f0206792e to your computer and use it in GitHub Desktop.
Save roughconsensusandrunningcode/7c206092760ce07ebc12094f0206792e to your computer and use it in GitHub Desktop.
C# - An ObjectResult that when executed will produce a Too Many Requests (429) response with an optional Retry-After header.
namespace Microsoft.AspNetCore.Mvc;
/// <summary>
/// An <see cref="ObjectResult"/> that when executed will produce
/// a <see cref="StatusCodes.Status429TooManyRequests"/> response
/// with an optional Retry-After header.
/// </summary>
[DefaultStatusCode(DefaultStatusCode)]
public class TooManyRequestsObjectResult : ObjectResult
{
private const int DefaultStatusCode = StatusCodes.Status429TooManyRequests;
public TimeSpan? RetryAfter { get; }
public TooManyRequestsObjectResult([ActionResultObjectValue] object value)
: base(value)
{
StatusCode = DefaultStatusCode;
}
public TooManyRequestsObjectResult([ActionResultObjectValue] object value, int retryAfter)
: this(value, TimeSpan.FromSeconds(retryAfter))
{
}
public TooManyRequestsObjectResult([ActionResultObjectValue] object value, TimeSpan retryAfter)
: this(value)
{
if (retryAfter < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(retryAfter), $"{nameof(retryAfter)} must be a non negative value");
}
RetryAfter = retryAfter;
}
public override Task ExecuteResultAsync(ActionContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (RetryAfter.HasValue)
{
context.HttpContext.Response.Headers.RetryAfter = Math.Round(RetryAfter.Value.TotalSeconds).ToString();
}
return base.ExecuteResultAsync(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment