Search code examples
c#apitimercontrollerhttprequest

How can i call a HttpRequest from a C# class?


I have a timer which i want to call a method. Is there a way to accomplish this?

I have a timer on server side which when the timer ends i want to add points to all members inside a sql database.

TIMER

 private async Task DoWorkAsync()
        {
            try
            {
                while (await _timer.WaitForNextTickAsync(_cts.Token))
                {
                    // Here i want to call AddPointsToAllMembers();
                }
            }
            catch (Exception ex) { 
                Console.WriteLine(ex.ToString());
            }
        }

Method i want to call

 // Adds points to all members
[HttpGet("members")]
public void AddPointsToAllMembers()
{
   try
   {
                string conString = _configuration.GetConnectionString("MembershipApp");
                MySqlConnection conn = new MySqlConnection(conString);
                conn.Open();
                
                string sqlCommand = "SELECT * FROM member";
                MySqlCommand cmd = new MySqlCommand(sqlCommand, conn);
                MySqlDataReader dReader = cmd.ExecuteReader();

                while (dReader.Read())
                {
                    SetPoints(50, (long)dReader[2]);
                }
                dReader.Close();
                
                conn.Close();
    }
    catch (Exception ex)
    {
                Console.WriteLine(ex.ToString());
    }
}

Solution

  • The HttpClient class. Make a static instance of it and send it a request using GetStringAsync with the full url.

    In the class with the DoWorkAsync method:

    private static readonly System.Net.HttpClient client = new();
    
    // when you want to invoke the end point
    string status = await client.GetStringAsync("http://[yourdomain].com/points/members");
    

    I'm just guessing at your controller url and end point for points, change it as needed.

    You can also grab the return string from the client if you care about any kind of status/response from the end point.