当我使用Web API从匿名类返回数据时,我对返回类型使用什么?

时间:2013-04-10 12:51:25

标签: asp.net-mvc asp.net-mvc-3 asp.net-web-api

我有以下ASP MVC4代码:

    [HttpGet]
    public virtual ActionResult GetTestAccounts(int applicationId)
    {
        var testAccounts =
            (
                from testAccount in this._testAccountService.GetTestAccounts(3)
                select new
                {
                    Id = testAccount.TestAccountId,
                    Name = testAccount.Name
                }
            ).ToList();

        return Json(testAccounts, JsonRequestBehavior.AllowGet);
    }

现在我正在将其转换为使用Web API。为此可以有人告诉我 如果我在这里返回一个匿名类,我的返回类型应该是什么?

1 个答案:

答案 0 :(得分:5)

它应该是HttpResponseMessage

public class TestAccountsController: ApiController
{
    public HttpResponseMessage Get(int applicationId)
    {
        var testAccounts =
            (
                from testAccount in this._testAccountService.GetTestAccounts(3)
                select new 
                {
                    Id = testAccount.TestAccountId,
                    Name = testAccount.Name
                }
            ).ToList();

        return Request.CreateResponse(HttpStatusCode.OK, testAccounts);
    }
}

但良好实践要求您应该使用视图模型(顺便说一句,您应该在ASP.NET MVC应用程序中完成):

public class TestAccountViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

然后:

public class TestAccountsController: ApiController
{
    public List<TestAccountViewModel> Get(int applicationId)
    {
        return
            (
                from testAccount in this._testAccountService.GetTestAccounts(3)
                select new TestAccountViewModel 
                {
                    Id = testAccount.TestAccountId,
                    Name = testAccount.Name
                }
            ).ToList();
    }
}