我必须编写一个小小的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 –