2017-03-17 86 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