Last active
May 15, 2023 14:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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