[英]C# Http Post receive json from body
我有這個HttpPost方法:
[HttpPost]
public string Test([FromBody]List<Account> accounts)
{
var json = JsonConvert.SerializeObject(accounts);
Console.Write("success");
return json;
}
這是我的Account類:
public class Account
{
public int accountId;
public string accountName;
public string createdOn;
public string registrationNumber;
}
這是我與郵遞員發送的json文件:
{
"Account": [
{
"accountId": "1",
"accountName": "A purple door",
"createdOn": "25-07-2017",
"registrationNumber": "purple"
},
{
"accountId": "2",
"accountName": "A red door",
"createdOn": "26-07-2017",
"registrationNumber": "red"
},
{
"accountId": "3",
"accountName": "A green door",
"createdOn": "27-07-2017",
"registrationNumber": "green"
},
{
"accountId": "4",
"accountName": "A yellow door",
"createdOn": "25-07-2017",
"registrationNumber": "yellow"
}
]
}
如果我發送此json,則我的方法無效,它將返回一個空對象。 使其正常工作的唯一方法是僅發送不帶“帳戶”的對象,如下所示:
[
{
"accountId": "1",
"accountName": "A purple door",
"createdOn": "25-07-2017",
"registrationNumber": "purple"
},
{
"accountId": "2",
"accountName": "A red door",
"createdOn": "26-07-2017",
"registrationNumber": "red"
},
{
"accountId": "3",
"accountName": "A green door",
"createdOn": "27-07-2017",
"registrationNumber": "green"
},
{
"accountId": "4",
"accountName": "A yellow door",
"createdOn": "25-07-2017",
"registrationNumber": "yellow"
}
]
但是我想要以前的文件格式。 我的方法如何接收以前的JSON?
嘗試使用此合同來滿足您的要求。
public class Rootobject
{
public Account[] Account { get; set; }
}
public class Account
{
public string accountId { get; set; }
public string accountName { get; set; }
public string createdOn { get; set; }
public string registrationNumber { get; set; }
}
方法應該是這樣的。
[HttpPost]
public string Test([FromBody]Rootobject accounts)
{
var json = JsonConvert.SerializeObject(accounts);
Console.Write("success");
return json;
}
為您的Account類添加一個包裝器並更改方法定義
public class Account
{
public int accountId;
public string accountName;
public string createdOn;
public string registrationNumber;
}
public class AccountWrapper
{
public List<Account> Accounts { get; set; }
}
public string Test([FromBody]AccountWrapper accounts)
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.