System.OperationCanceledException: The operation was canceled.

Vuyiswa Maseko 351 Reputation points
2021-10-05T21:01:06.893+00:00

Good Day All

i have the following code, that randomly throws the following error

System.OperationCanceledException: The operation was canceled.

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient httpClient = new HttpClient();

public async Task<List<USERS>> Get_All_Customers( )
{

             List<USERS> results = null;
             try
             {
                 USERS m_model = new USERS
                 {
                     USER_ID = 1,
                     CURRENT_DATETIME = '2021/07/01'
                 };
                 var httpClient = new HttpClient();

                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                 var Json = JsonConvert.SerializeObject(m_model, new JsonSerializerSettings
                 {
                     ContractResolver = new DefaultContractResolver
                     {
                         IgnoreSerializableAttribute = false
                     }
                 });


                 HttpContent httpContent = new StringContent(Json, Encoding.UTF8, "application/json");
                 httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");

var response = await httpClient.PostAsync(string.Format("https://www.myserver.com/api/MainCustomers_OnlineDates/Get_All_Customers"), httpContent);

                 if (response.StatusCode == System.Net.HttpStatusCode.OK)
                 {
                     var content = await response.Content.ReadAsStringAsync();
                     results = JsonConvert.DeserializeObject<List<USERS>>(content);
                 }
             }
             catch (Exception ex)
             {
                 await Task.Run(() => Crashes.TrackError(ex));
             }

             return results;
         }

Thanks

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,294 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
294 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,686 Reputation points
    2021-10-06T20:21:55.917+00:00

    also why line 9 when you declared a static as preferred?