[英]Return JSON as a response for HTTP Get in ASP.NET WebApi Controller
我可以收集一些變量並列出並放入JSON中,如果HTTP Get調用成功,該變量將返回給客戶端嗎?
例如:
我有這個控制器,它必須返回帳戶列表和更多的值:
public class BankAccountController : ApiController
{
[Authorize]
[Route("/accounts")]
public IHttpActionResult GetAccounts()
{
List<Account> userAccounts = new List<Account>{
new Account {
AccountNumber = 1,
Available = 2346.220m,
Balance = 3219.12m,
Currency = "euro",
InterestRate = 1,
Name = "Current account",
Type = ""},
new Account {
AccountNumber = 2,
Available = 12346.220m,
Balance = 32219.12m,
Currency = "euro",
InterestRate = 3,
Name = "Saving account",
Type = ""},
new Account {
AccountNumber = 3,
Available = 346.220m,
Balance = 219.12m,
Currency = "euro",
InterestRate = 3,
Name = "Current account",
Type = ""},
new Account {
AccountNumber = 4,
Available = 37846.220m,
Balance = 21943.12m,
Currency = "euro",
InterestRate = 3,
Name = "Saving account",
Type = ""},
new Account {
AccountNumber = 5,
Available = 137846.220m,
Balance = 21943.12m,
Currency = "euro",
InterestRate = 3,
Name = "Saving account",
Type = ""},
new Account {
AccountNumber = 6,
Available = 7846.220m,
Balance = 21943.12m,
Currency = "euro",
InterestRate = 3,
Name = "Current account",
Type = ""}
};
var currentAccountsTotal = userAccounts.Count();
string currentsAccountTotalCurrency = "something";
string savingsAccountTotalCurrency = "something";
decimal savingsAccountsTotal = userAccounts.Where(a => a.Name == "Saving account").Select(b => b.Balance).Sum();
return ?;
}
我可以將userAccounts列表,currentAccountsTotal,currentsAccountTotalCurrency和SavingsAccountsTotal放入將返回到客戶端的JSON中嗎?
我有呼叫規范,它看起來像這樣:在200個代碼上,我將JSON中提到的所有內容返回給客戶端。
在這種情況下,我應該把什么作為返回值?
您需要了解的內容:開箱即用,webapi支持內容協商的概念。
什么是內容協商? 內容協商是選擇最佳表示形式(JSON,XML等)的過程。
如何在WebAPI中完成? 基本上,它正在讀取accept標頭。
例:
Accept: application/xml
如果webapi找到該請求的任何格式化程序,它將根據用戶請求格式化響應。
您可以添加或刪除格式器,例如,如果要始終使用json,則應刪除xml格式器,如下所示:
config.Formatters.Remove(config.Formatters.XmlFormatter);
如果需要,您還可以創建自己的格式化程序,並將其添加到配置中。
在代碼中,您只需要返回對象或Ok()即可,具體取決於您將什么用作返回類型。
在您的情況下,我們可以使用匿名對象,也可以請求自己的DTO來表示您的響應,該響應將這三個對象放在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.