Feedback and possible better method for my get and post requests in C# using httpclient
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.
c# httpwebrequest httpclient system.net.httpwebrequest
|
show 8 more comments
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.
c# httpwebrequest httpclient system.net.httpwebrequest
Your get & add methods are completely useless.
– SLaks
Nov 19 '18 at 19:30
1
Do not useasync void
.
– SLaks
Nov 19 '18 at 19:30
1
@mikecmr Placing your request methods in a separate class would be beneficial, especially if you need to re-use them in another project. Also, as SLaks mentioned, you should return aTask
in anasync void method
, so instead ofasync void
doasync Task
– Ryan Wilson
Nov 19 '18 at 19:33
1
@MikeCMR As far as I know this seems correct. If you wanted to make this even more re-useable, you could build your own API which handles sending the requests to the other APIs, then you could just call your custom API from any project.
– Ryan Wilson
Nov 19 '18 at 19:58
1
@MikeCMR Here is a getting started article off of Microsoft's Documentation for creating an API with dotnet core: (docs.microsoft.com/en-us/aspnet/core/tutorials/…). I would start there and go through that first. Then if you need more help, you can always post new questions here, there are a lot of documents and tutorials out there for building an API.
– Ryan Wilson
Nov 19 '18 at 20:14
|
show 8 more comments
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.
c# httpwebrequest httpclient system.net.httpwebrequest
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.
c# httpwebrequest httpclient system.net.httpwebrequest
c# httpwebrequest httpclient system.net.httpwebrequest
asked Nov 19 '18 at 19:28
CMRCMR
558
558
Your get & add methods are completely useless.
– SLaks
Nov 19 '18 at 19:30
1
Do not useasync void
.
– SLaks
Nov 19 '18 at 19:30
1
@mikecmr Placing your request methods in a separate class would be beneficial, especially if you need to re-use them in another project. Also, as SLaks mentioned, you should return aTask
in anasync void method
, so instead ofasync void
doasync Task
– Ryan Wilson
Nov 19 '18 at 19:33
1
@MikeCMR As far as I know this seems correct. If you wanted to make this even more re-useable, you could build your own API which handles sending the requests to the other APIs, then you could just call your custom API from any project.
– Ryan Wilson
Nov 19 '18 at 19:58
1
@MikeCMR Here is a getting started article off of Microsoft's Documentation for creating an API with dotnet core: (docs.microsoft.com/en-us/aspnet/core/tutorials/…). I would start there and go through that first. Then if you need more help, you can always post new questions here, there are a lot of documents and tutorials out there for building an API.
– Ryan Wilson
Nov 19 '18 at 20:14
|
show 8 more comments
Your get & add methods are completely useless.
– SLaks
Nov 19 '18 at 19:30
1
Do not useasync void
.
– SLaks
Nov 19 '18 at 19:30
1
@mikecmr Placing your request methods in a separate class would be beneficial, especially if you need to re-use them in another project. Also, as SLaks mentioned, you should return aTask
in anasync void method
, so instead ofasync void
doasync Task
– Ryan Wilson
Nov 19 '18 at 19:33
1
@MikeCMR As far as I know this seems correct. If you wanted to make this even more re-useable, you could build your own API which handles sending the requests to the other APIs, then you could just call your custom API from any project.
– Ryan Wilson
Nov 19 '18 at 19:58
1
@MikeCMR Here is a getting started article off of Microsoft's Documentation for creating an API with dotnet core: (docs.microsoft.com/en-us/aspnet/core/tutorials/…). I would start there and go through that first. Then if you need more help, you can always post new questions here, there are a lot of documents and tutorials out there for building an API.
– Ryan Wilson
Nov 19 '18 at 20:14
Your get & add methods are completely useless.
– SLaks
Nov 19 '18 at 19:30
Your get & add methods are completely useless.
– SLaks
Nov 19 '18 at 19:30
1
1
Do not use
async void
.– SLaks
Nov 19 '18 at 19:30
Do not use
async void
.– SLaks
Nov 19 '18 at 19:30
1
1
@mikecmr Placing your request methods in a separate class would be beneficial, especially if you need to re-use them in another project. Also, as SLaks mentioned, you should return a
Task
in an async void method
, so instead of async void
do async Task
– Ryan Wilson
Nov 19 '18 at 19:33
@mikecmr Placing your request methods in a separate class would be beneficial, especially if you need to re-use them in another project. Also, as SLaks mentioned, you should return a
Task
in an async void method
, so instead of async void
do async Task
– Ryan Wilson
Nov 19 '18 at 19:33
1
1
@MikeCMR As far as I know this seems correct. If you wanted to make this even more re-useable, you could build your own API which handles sending the requests to the other APIs, then you could just call your custom API from any project.
– Ryan Wilson
Nov 19 '18 at 19:58
@MikeCMR As far as I know this seems correct. If you wanted to make this even more re-useable, you could build your own API which handles sending the requests to the other APIs, then you could just call your custom API from any project.
– Ryan Wilson
Nov 19 '18 at 19:58
1
1
@MikeCMR Here is a getting started article off of Microsoft's Documentation for creating an API with dotnet core: (docs.microsoft.com/en-us/aspnet/core/tutorials/…). I would start there and go through that first. Then if you need more help, you can always post new questions here, there are a lot of documents and tutorials out there for building an API.
– Ryan Wilson
Nov 19 '18 at 20:14
@MikeCMR Here is a getting started article off of Microsoft's Documentation for creating an API with dotnet core: (docs.microsoft.com/en-us/aspnet/core/tutorials/…). I would start there and go through that first. Then if you need more help, you can always post new questions here, there are a lot of documents and tutorials out there for building an API.
– Ryan Wilson
Nov 19 '18 at 20:14
|
show 8 more comments
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381370%2ffeedback-and-possible-better-method-for-my-get-and-post-requests-in-c-sharp-usin%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381370%2ffeedback-and-possible-better-method-for-my-get-and-post-requests-in-c-sharp-usin%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Your get & add methods are completely useless.
– SLaks
Nov 19 '18 at 19:30
1
Do not use
async void
.– SLaks
Nov 19 '18 at 19:30
1
@mikecmr Placing your request methods in a separate class would be beneficial, especially if you need to re-use them in another project. Also, as SLaks mentioned, you should return a
Task
in anasync void method
, so instead ofasync void
doasync Task
– Ryan Wilson
Nov 19 '18 at 19:33
1
@MikeCMR As far as I know this seems correct. If you wanted to make this even more re-useable, you could build your own API which handles sending the requests to the other APIs, then you could just call your custom API from any project.
– Ryan Wilson
Nov 19 '18 at 19:58
1
@MikeCMR Here is a getting started article off of Microsoft's Documentation for creating an API with dotnet core: (docs.microsoft.com/en-us/aspnet/core/tutorials/…). I would start there and go through that first. Then if you need more help, you can always post new questions here, there are a lot of documents and tutorials out there for building an API.
– Ryan Wilson
Nov 19 '18 at 20:14