Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core post form data to uri

Tags:

asp.net-core

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.

like image 205
big_water Avatar asked Dec 03 '22 22:12

big_water


1 Answers

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));
like image 75
tpeczek Avatar answered Dec 13 '22 18:12

tpeczek