A bit bothered by how I am doing this, and wanted some feedback on a better way.
Here is some code I wrote to post to a website, I will also show the get request as well.
So assuming you don't need to see when we construct the HttpClient, CookieContainer, and ClientHandler here is the code:
List<KeyValuePair<string, string>> ListLogin = new List<KeyValuePair<string, string>>(); //key value pair is the input name and then the input value to be used
ListLogin = AddToList("userid", "someUser", ListLogin);
ListLogin = AddToList("passwd", "somePassword", ListLogin);
ListLogin = AddToList("domain", "whoCares", ListLogin);
ListLogin = AddToList("destinationURL", "/", ListLogin);
IEnumerable<KeyValuePair<string, string>> QueryLogin = GetEnumerable(ListLogin);
PostRequest("URL.com", QueryLogin);
So the above is building the key value pair for what the server will expect. Then using the methods to construct the request.
I will also show the AddToList method:
public static List<KeyValuePair<string, string>> AddToList(string
strInput1, string strInput2, List<KeyValuePair<string, string>>
ListInput)
{
List<KeyValuePair<string, string>> NewList = ListInput;
NewList.Add(new KeyValuePair<string, string>(strInput1, strInput2));
return NewList;
}
Here is also the getEnumerable method:
public static IEnumerable<KeyValuePair<string, string>> GetEnumerable(List<KeyValuePair<string, string>> ListInput)
{
IEnumerable<KeyValuePair<string, string>> queriesNew = ListInput;
return queriesNew;
}
Finally the post and get request methods:
async static void PostRequest(string strUrl,
IEnumerable<KeyValuePair<string, string>> queries)
{
Uri uri = new Uri(strUrl);
cookieContainer.GetCookies(uri);
HttpContent q = new FormUrlEncodedContent(queries);
HttpResponseMessage response = await client.PostAsync(strUrl, q);
HttpContent content = response.Content;
string myContent = await content.ReadAsStringAsync();
// Console.WriteLine(myContent);
// Console.WriteLine(response);
IEnumerable<Cookie> responseCookies =
response.Dispose();
}
async static Task<String> GetRequest(string strUrl)
{
HttpResponseMessage response = await client.GetAsync(strUrl);
HttpContent content = response.Content; //content of the response
string myContent = await content.ReadAsStringAsync();
Console.WriteLine(myContent);
response.Dispose(); //dispose of the response
return myContent;
}
Just looking for some constructive criticism on my approach.When I am typing new get and post requests, it just feel repetitive, and I was under the impression usually if it feels repetitive, there might be a better way.And then to make this a bit of a two part question, the PostRequest and GetRequest methods.I think it would be better to put that into its own class so its reusable in other solutions/projects? Yay/nay?
A thank you in advance.