How do you post form data to an external url in .Net Core? For example, if I wanted to recreate this sample request:
POST
Url: www.googleapis.com/oauth2/v4/token
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=ABCD1234&
client_secret=XYZ1234&
redirect_uri=https://test.example.com/code&
grant_type=authorization_code
I found an example here that shows an example for posting JSON, but nothing for form data.
This can be done with HttpClient
from Microsoft.AspNet.WebApi.Client package as well by using FormUrlEncodedContent
:
IList<KeyValuePair<string, string>> nameValueCollection = new List<KeyValuePair<string, string>> {
{ new KeyValuePair<string, string>("code", "4/P7q7W91a-oMsCeLvIaQm6bTrgtp7") },
{ new KeyValuePair<string, string>("client_id", "ABCD1234") },
{ new KeyValuePair<string, string>("client_secret", "XYZ1234") },
{ new KeyValuePair<string, string>("redirect_uri", "https://test.example.com/code") },
{ new KeyValuePair<string, string>("grant_type", "authorization_code") },
};
client.PostAsync("www.googleapis.com/oauth2/v4/token", new FormUrlEncodedContent(nameValueCollection));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With