jeudi 19 septembre 2019

Looking for Design Pattern to Automate Repeated Task such as Login/Logout

I'm looking to a design pattern to help simplify my code.

My code is using HttpClient to call a web API that gets or posts information, but each session requires a login call first where a cookie is returned as ID, and a logout call is made at the end to close the connection. So my web API class looks like this:

public class APIHelper 
{
    public HttpClient myClient { get; set; }

    public async void Login()
    {
        using (HttpResponseMessage response = await myClient.PostAsync("loginAddress", "loginInput"))
        {
            if (response.IsSuccessStatusCode)
            {                    
                //save cookie
            }
        }
    }

    public async void Logout()
    {
        using (HttpResponseMessage response = await myClient.PostAsync("logoutAddress", ""))
        {
            if (response.IsSuccessStatusCode)
            {                    
                //session ends
            }
        }
    }

    public void GetOrder()  {...}

    public void NewOrder(object OrderData)  {...}

    public void GetCustomer()   {...}

    public void NewCustomer(object CustomerData)    {...}
}

And to use them, I would simply call them in order:

public Main()
{
    APIHelper.Login();
    APIHelper.GetOrder();   //or NewOrder, or GetCustomer, or any other actual API calls
    APIHelper.Logout();
}

Is there anyway I can place the Login/Logout calls inside each of the actual API calls so I don't have to type them up for each call? Ideally I just have to set up the structure once, then for whatever API calls I create, the system will automatically call the Login/Logout at beginning/end. Which design pattern addresses this kind of issue? Any simple example would be very helpful!

Thank you. SC

Aucun commentaire:

Enregistrer un commentaire