Http Get And Post In C#
HTML-код
- Опубликовано: 22 сен 2024
- Making an GET or POST Request is easy in C# thanks to the HttpClient object. See how you can build simple requests in .NET.
HTTP GET and HTTP POST are essential components of any web application, and this video will help you learn how to create a simple REST API using C#. By the end of this video, you'll be able to create a basic HTTP GET and HTTP POST REST API using C#.
If you're new to programming or want to learn more about the basics of the HttpClient library, this video is for you! By the end of the video, you'll be able to create simple HTTP GET and HTTP POST calls using C#, and understand the basics of the REST API. Thanks for watching!
For info on IDispose and the dispose pattern in C#, check out my blog post here:
#csharp #dotnet #programming #coding #softwaredevelopment #softwareengineering #coders #tutorials
year worth of university lectures in a 20 minutes. YOU ARE THE MAN.
Not only did you explain it well, but you are super personable. I hope you have a lot of success with your RUclips channel.
Thanks for the kind words! Really glad you found it useful. Please let me know if you have any requests for other specific content
That was a really good lesson and I learnt a lot. You explain things incredibly well and I hope you keep posting. *Subscribed.* .
Thanks! Really glad it helped and thanks for the sub! Let me know if there are any specific topics you'd like me to cover in future
I admire such an explanation, to the core exactly what is needed in plain english. Extemely clear and valuable explanation, all the words from you when you explain are very important.
Thank you so much!
Just brilliant Nick, thank you! And your teaching manner would have to be one of the best on RUclips!
I "only had to do" a simple (!?) POST and GET via our C# Server application to/from an IoT "Things Board".
Wasted most of the weekend (it's now 5:00am Monday in Aus.) going round in circles until I found your link: Solved in less than 1hr😀
Bonus: I now understand exactly what is happening; not just a blind cut-and-paste.
Fantastic! Really great words and I hope it brings you back for more content. Let me know what else you'd like to see on the channel :)
@@nickproudprogrammer Thank you. It certainly will bring me back 🙂
Omg i love people like you who explain like this, simple code, everything is perfect thank you men
Pleasure!
So Nick l am gratefull to you for this video man and please don't stop .l know you just get a little money from youtube but we really need your help , thx bro
I'm truly grateful for your support! It means a lot to know that my videos are making a difference. I’ll definitely keep them coming!
hi, thanks for the video. i looking for this almost 3hours
Thanks a lot, I've been trying to work with Api's for a while now. But I have never understand every step of the process. This is the first time I've found an explanation for each Expression and Statement.
Well, again some random guy rescues the day. :D
Thanks man! That was exactly what i was looking for.
My pleasure! Hope I can help you out again in future
I looked for weeks for a good and clean explanation of this, thank you so much. Please keep it up bud and again thank you so much.
My pleasure. I'm so glad it helped. Makes it all worth it!
@@nickproudprogrammer To give as much insight as I can to help from my noob self the step by step helps a lot, other videos out there gloss over too much because they know it so they think "I don't need to talk about it". I know a lot programing tends to be very abstract but the more visual the better just like most learn video games by pushing buttons and seeing what they do. I know this might be hard but info is power and thank you again :)
Just what I needed for my client. Just needed to add the SecurityProtocol and I was all set. Thanks again!
Great to hear!
Mate, it’s bad practice to wrap HttpClient in a Using statement and definitely shouldn’t be implemented in production code.
Thanks.
This is knowledge with explication for every possible click! I haven't been able to get it from anybody else !
Thank you a lot !
You're welcome!
Guide how to post Authorized Api which required header and detail as RawBody format
Thanks so much for the video, was really struggling with doing these HTTP requests since I've never done them before and this really helped out.
Glad it helped!
Man... You just saved me...
I'm here the whole day at that dumb part of the code just for get a simply json back from a API.
The more I learn other programming languages, more I love Python...
Sorry for that. But thank you!
You're so welcome, and I'm so glad this helped 😁
Very good lesson as explained very clear.
Thanks Nick, just what I was looking for. The Async bit was catching me out, the .Result was the missing bit for me.
My pleasure! I'm glad it was useful :)
This is super http client explanation
It took me 2 years and 20 mins to understand it you did it in 20 mins
Thank you very much, great video and exactly what I needed!
Thanks . My concept got more clearer.
Thanks, Nick, for posting this excellent video. It is really helpful to me.
Thank you so much for your kind words! I'm glad to hear that the video was helpful to you. If you have any other topics you'd like me to cover, let me know!
Hi, Thanks for the nice tutorial. How should I add multiple headers in the request?
That was such a good explenation that even a Python bro could understand it (me). Thnx mate cheers
Haha! Glad you liked it
Thank you, brother, you helped me figure out a lot.
Very clear explanation great video and easy to understand...👌🏻👌🏻👌🏻
Thanks a lot 😊
You should not use HttpClient with an using statement.
Otherwise it could cause a SocketException due to Socket Exhaust.
great music 💜💀💎
Very clearly explained Thank you!
Thank you! Glad it was helpful 👍
You Got sent amazing man. Thanks =)
Thank you!
Very welcome!
Thank you!
You're welcome!
very good lesson for the beginners. Thanks!
You're very welcome!
Thanks for this.
Absolutely brilliant explanation!
Many thanks!
keep going man.nice tutorial
Thanks, will do!
Awesome, really informative
Glad it was helpful!
Im not sure if you are still checking the comments on this but I saw somewhere else someone talking about not putting your HTTP client in a using statement cause "it isn't the kind of object you want to instanciate a lot" but you are saying that you should. Could you elaborate if one of these ways is better
very good video heres a like !
Thank you!
Thanks, code works well
very helpful thanks !
pretty neat. i am completly new to this stuff. maybe someone can help me out.. how do i split the json into seperate datas? placeholder for example gives id, titel, body and user id. how do i read the id from that json and set it as an integer in c#?
Thanks!
Hey thank you for the super thanks! Appreciate ya 🙏
That was a really great explanation, thank you! I have struggled with this for a while and I am currently working on a student project to write a simple client / server application using http protocol but instead of serving to a url / web client I am just updating an object in a local datastore. Is it possible to adapt this tutorial to suit those needs? And if so, would you consider adding some examples of that to this project? Thanks again
Hi! Thanks for the kind feedback!
I'm not sure I fully understand your use case. Could you provide some more detail on what you're trying to achieve? Then I could look at making something for you :)
thanks for a clear explanation.
You are welcome!
Hi Nick
Thank you for your simple but powerful explanation.
I am trying to follow your code to connect with Bearer token,
but don't know where to put the Token information.
Can you please show me where and how to call it.
Thank you again
You should be able to set the 'Authorization' property of the http client's 'DefaultRequestHeaders' as below. (Remember to either use a HttpClientFactory or static HttpClient and NOT a using statement. This prevents port exhaustion). - and obviously ensure your client is disposed of when you're finished with it 👍
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "Your token");
Excellent!!!
Awesome!
really helpfull, thanks my guy
My pleasure! Thanks for watching. I'm really glad it helped and I hope I can help again :)
Very helpful! Thank you!
Hi, tks for video...I would like a question. If Post Class has three property(Title, Body and UserId), what represents "id":101?
{
"Title": "Test Post",
"Body": "Hello World!",
"UserId": 44,
"id": 101
}
Tks for answers...
So everything in your lesson works for me, but when I try to reach my own endpoint it results in an error 400, but the demo automatically generated with swagger works, wtf
Are you sending a payload of some sort? If so is it valid? Might be the difference between what you're doing from scratch and within Swagger
Hi Nick. Thank you very much for the vídeo. I have a question. Looking at The string at 9 minutes in the vídeo. Let's say I want to put objects with these attributes in a list. How would I do that?
How to deserialze json to c# object ?
Great suggestion. I'll be making a video on this soon
@@nickproudprogrammer thanks sir but I need it badly. I tried all youtube tutorial even in google and stack overflow. But none of them work with my code. I hope you will upload asap for my thesis project.
I already figure out thanks anyway sir nick!
@@garudakurt5166 great! Glad you're all set
Could you show an example with authentification? I'm trying for a while to log into Magento 2 with admin token ... Nothing helps, even stackoverflow.
What is the name of the token header you need to send? Are you using any specific Magento api documentation?
Really helpfull, thank you buddy
great learning. very thank you. one question about i got stuck is that how to get only id value like 101 from this return result set at 18:49 video time. plz guide.
You can use NewtonSoft Json for this with JObject.Parse. Take a look at this link. It would be JObject.Parse("id").ToString() www.newtonsoft.com/json/help/html/m_newtonsoft_json_linq_jobject_parse.htm
Can I use this method using WPF? thanks in advanced!!
That was a really great explanation, thank you!, thank you!
Could you show an example how to upload xml file to endpoint?
Thank you.
Funny you should ask, there is a mention on how to do this in a video I'm releasing next week on Wednesday. Stay tuned!
@@nickproudprogrammer Thank you!
nice
Thanks
Thank you for the wonderful explanation! May I ask why would you choose ".Result" instead of "await" here?
If you wanted to run the method synchronously, then you'd use .Result like I did, and really, this was just for the video to keep my code running easily for debug. In practice, I would use await by default.
Blog post link doesn't work.
The Best
Hi Nick!
I've been struggling with getting a json from an api, could you please help me?
Sure. Are you getting an error message? Send some details of the issue via my website and I'll take a look - www.automationmission.com/contact/
how get a IMG in C# with the method GET?
Depends on the API. Would need more info. Send some details of the issue via my website and I'll take a look - www.automationmission.com/contact/
Hello Nick, amazing tutorial.
Yet I'm getting the following result response:
Id = 19, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
Any clues on the solution of that?
Sounds like you're calling an async method without awaiting it. Use await or if you want to run it synchronously, use .Result at the end of the method
@@nickproudprogrammer worked like a charm, thanks a lot!
@@rodrigomoro8047 Great!
Great video Thanks a lot
I only have one question
How can I post an already existing json file using this post method ?
Use the System.IO namespace to read the json file as text. System.IO.File.ReadAllText(yourFilePath)
Then use that text as the payload with Content-Type set to 'application/json'
How i read Active html with c#? For example when i login to the website i want to get html
You should be able to use a GET request on any url to get the html content. Then you could use something like the HTMLAgilityPack to parse the returned HTML html-agility-pack.net/
@@nickproudprogrammer i already used that agility package but it just reading First html content
@@nickproudprogrammer cant i read active Google Chrome html content ? Is it possible
@@judgedev2789It's tricky with google, because http requests usually end up being shown the initial 'consent' window. You may want to look into an RPA solution like UIPath to automate getting through the google search page and then scraping the html
@@nickproudprogrammer thanks man i will look into it
Thank you so much
That is a very good lesson. Thank you very much.
I need to set a cookie on the Get request, can you please help
Hello Nick, thank you for the video, very good explanation. But as my url is authenticated as bearer token, how can I do that ?
Depends on how it's expecting the token to be sent. Do you have documentation for your API or is it publicly available? Or is it private?
@@nickproudprogrammer Unfortunatly, I don't have any documentation about it. But I have managed to solve it. I have used the Dictionary and it worked. Thank you again
How to add authenticate while posting process Coudl you explain that please
Depends on the authentication type in use. What are you using? Basic, OAuth? etc
This is cool.
It's support TLS 1.3?
Should do, but if you need to specify specific TLS version: System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls13
If we can't see Post.cs, give link to source code please
Thanks
No problem
Although HttpClient implements IDisposable you SHOULD NOT wrap it within an Using statement. In fact, it is extremely BAD practice to do this as connections aren’t released straight away which can cause network exhaustion and DNS issues when called in high volumes. The correct way to use HttpClient is reusing it with HttpClientFactory. It saddens me that so many programmers do not know how to use HttpClient properly and why it shouldn’t follow the IDisposable pattern. What’s worst are people commenting that it’s a great video, implement it and unaware that it’s incorrect and bad practice.
HI it worked well many thanks for this video but my code shows an error System.Net.WebExceptiom. The remote server returned an error. I think it needs the code username and password? cus my API has a username & password can u do a video of it or provide the source code pls?
WHATS VAR NEWPOST = NEW POST()
hello
hi
the use of var is WAY TO MUCH
ddd
dd
ssss
xxxx
fddf
dafuq you wasted 19.36 minutes of my life to explain something that could be done in under 5 minutes ............GET GOOD SON
this video as helped me a lot and I was able to do both get and post request with already created endpoints. Thank you!
I am working on something new and am using your POST method but I am getting the error back {"detail":"Authentication credentials were not provided."} I am trying to send a POST request to get a bearer token back. and the javascript they sent me looks as follows; any suggestions? also under my headers in postman for KEY: Authorization it then has VALUE: Basic kdfjjsdfASDFASD34234DASd== So am not sure how I would send that Basic Auth to return the client_credentials
pm.sendRequest(
{
"url": `${base_url}/quote/auth`,
"method": 'POST',
"header": {
"Content-Type": "application/json",
"Authorization": `Basic ${btoa(basic_auth_cred)}`,
},
"body": {
"mode": "raw",
"raw": JSON.stringify({
"auth_type": "client_credentials",
}),
}
}, function (err, response) {
const response_data = response.json();
if (response_data.access_token === undefined) {
throw new Error("No access token recieved.");
}
pm.request.headers.add({
name: "Authorization",
key: "Authorization",
value: `Bearer ${response_data.access_token}`,
});
}
);
Actually with your video and one online source I was able to get the client credentials back! Thank you for this video!!
Now that I have the bearer token, I am going to have to do a GET request using the bearer token to a new endpoint.
Amazing!
Really bad tutorial if you have to use another REST Framework that basically does all the work for you. Really should be called how to Post in Newtonsoft.
Not just that. Wrapping HttpClient in an Using statement is NO, NO, NO.
Awesome!
Thank you! Cheers!
ssss
ssss