'C# (429) Too Many Requests
I've been using the WebClient in C# to get specific data from a webpage. That works well until I do it more than 2 times. If I do it more than more than 2 times it gives me the "(429) Too Many Requests." error. I have looked at other questions regarding this issue, by the way.
Solution 1:[1]
I know that this thread is quite old. but I wanted to share solutions
Maybe you can try polly as interceptor to retry the request.
for the policy handler
serviceCollection.AddHttpClient<IExternalAPI, ExternalAPI>(client =>
{
var url= "";
url = config.GetSection("Config").GetValue<string>("baseUrl");
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}).AddPolicyHandler((provider, request) =>
{
return Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.TooManyRequests)
.RetryAsync(1, async (response, retryCount, context) =>
{
if (response.Result.StatusCode == HttpStatusCode.Unauthorized)
{
// Add delay here
Thread.Sleep(1000);
Logger.LogInformation("Unauthorized Request Occured, Re-authenticating");
await client.Authenticate();
}
// refresh auth token.
Solution 2:[2]
This post is old, but I had the same issue downloading images from my webserver. I found the solution on this post
// THIS LINE IS THE IMPORTANT ONE
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
"Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
"InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";
I haven't had any issues since.
Solution 3:[3]
I recomend to use this code. it's not freezes GUI (wait for 15 seconds):
DateTime Tthen = DateTime.Now;
do
{
//Your code or nothing...
Application.DoEvents();
}
while (Tthen.AddSeconds(15) > DateTime.Now);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mel Bryan Flores |
| Solution 2 | Marc |
| Solution 3 | BestDeveloper |
