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

2 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);
    }
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*rov 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是好的做法要求你应该使用视图模型(顺便说一句,你应该在你的ASP.NET MVC应用程序中完成):

public class TestAccountViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)