2017-03-17 97 views
0

如何在.Net Core中將表單數據發佈到外部URL?例如,如果我想重新創建此示例請求:.Net Core發佈表單數據到uri

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 

我發現顯示張貼JSON一個例子爲例here,但沒有對錶單數據。

回答

2

這可以用HttpClientMicrosoft.AspNet.WebApi.Client包使用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)); 
+0

此代碼不能編譯,但是當你解決它它的工作原理。你必須做'新的KeyValuePair <字符串,字符串>(「client_id」,「ABCD1234」),'初始化列表。如果你想進行編輯,那麼我會接受,答案。謝謝! –

+0

@big_water固定,我匆忙的過錯:D – tpeczek