2

我有以下 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。为此,如果我在这里返回一个匿名类,有人可以告诉我我的返回类型应该是什么?

4

1 回答 1

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();
    }
}
于 2013-04-10T12:54:15.580 回答