Why I got 401 occasionally?

winanjaya 146 Reputation points
2023-02-06T00:29:25.2566667+00:00

Hi All,

I'm calling HTTPClient with dynamic token in a loop, but occasionally it thrown me 401 (Unauthorized).

  • What did I do wrong in my test codes below?
  • Is it correct to put the Authorization in there?, it looks like in some time it doesn't reset the token.

I need advice.

thank you so much in advance.

Win

Testingonly.cs
==============
List<Task> tasks = new List<Task>();

for (int i =0; i<100; i++)
{
   string token = getToken(i);
   tasks.Add(Models.Test.CheckHTTP(token));
}

await Task.WhenAll(tasks);

Test.cs
=======
public static async Task<bool> CheckHTTP(string token)
{
   string baseAddress = _httpClient.BaseAddress.ToString();
   

   List<Task> tasks = new List<Task>();
   bool _ok = true;
   do
   {
      await _httpClient.GetAsync(url).ContinueWith(async (c) =>
      {
            var response = await c;

            if (response.IsSuccessStatusCode)
            {
                // do some process
                tasks.Add(Do_SomeProcessAsync(response.Content.ReadAsStringAsync()));
            }
            else
            {
                SaveToFails(url, (int)response.StatusCode); // save the fails to a table
               _ok = false;
            }
       });
   }
   while(_ok);
 
   await Task.WhenAll(tasks);
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,251 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,233 questions
{count} votes

1 answer

Sort by: Most helpful
  1. winanjaya 146 Reputation points
    2023-02-06T07:32:39.91+00:00

    @Reza Aghaei

    thank you, I have created another question that related to this