我必須編寫一個小小的C#控制檯應用程序(但我的.NET知識幾乎爲NULL)來向PHP API發出POST請求,爲此我使用HttpClient實例。該API接受這樣c#字典作爲哈希表的值
{
"User": {
"email": "[email protected]",
"password": "something"
},
"Establishment": {
"id": 147
}
}
一個JSON做就怎麼做一些這方面的研究是我到目前爲止已經完成後是這樣的:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://italdelo.web.development.co/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// HTTP POST
Dictionary<string, string> user = new Dictionary<string, string>();
Dictionary<string, int> establishment = new Dictionary<string, int>();
HashTable postdata = new HashTable();
user.Add("email","[email protected]");
user.Add("password","something");
establishment.Add("id",147);
postdata.Add("User",user);
postdata.Add("Establishment",establishment);
HttpResponseMessage response = await client.PostAsJsonAsync("apiname/service", postdata);
response.EnsureSuccessStatusCode(); // Throw if not a success code.
}
catch (HttpRequestException e)
{
Console.WriteLine("Exception details: " + e.ToString());
}
}
}
運行這段代碼,我得到這個錯誤信息:
Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'HashTable' could not be found (are you missing a using directive or an assembly reference?) ProjectName C:\Users\...\Program.cs 47 Active
我知道錯誤是我想要設置的JSON發送到API,這是一個包含值(哈希表的鍵值符號)辭書散列表的方式。我很確定這是愚蠢的,但我真的不知道如何設置這個JSON的API,我沒有選擇,我需要使用C#。你能幫我請給我一些關於如何解決這個問題的建議,或以另一種方式完成這項工作嗎?提前致謝。
一種常見的方法是創建對象(用戶,建立,等等),然後用Json.Net序列化你的對象。 http://www.newtonsoft.com/json –