【发布时间】:2015-02-26 09:59:36
【问题描述】:
我可以收集一些变量并列出并将其放入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 list、currentAccountsTotal、currentsAccountTotalCurrency、savingsAccountsTotal 放入一些 JSON 中返回给客户端吗?
我有调用规范,它看起来像这样:在 200 代码上,我将 JSON 中提到的所有内容返回给客户端。
在这种情况下我应该把什么作为返回值?
【问题讨论】:
-
可以使用匿名变量吗?即:
return Ok(new { userAccounts = userAccounts , something = foo1, somethingelse = foo2}); -
@Stefan 嗯,我会这样尝试 :) 感谢您的建议 :)
标签: c# asp.net json asp.net-web-api