【问题标题】:What do I use for a return type when I am returning data from an anonymous class with Web API?当我使用 Web API 从匿名类返回数据时,我使用什么作为返回类型?
【发布时间】:2013-04-10 21:01:48
【问题描述】:

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

【问题讨论】:

  • 我会“包装”这个函数并让它返回一个强命名类型。另一端可以在可序列化时解释该类型。通过包装,您不必在应用程序中编辑公开 API 的代码。

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


【解决方案1】:

应该是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();
    }
}

【讨论】:

  • @PabloRomeo,是的,这正是它的阅读方式。感谢您发现这一点。我已经更新了我的答案。
  • 我同意,如果您要返回 HttpResponseMessage 以外的类型,那么它绝对应该是某种视图模型,但我不同意这是返回 @987654326 的最佳实践@,只是使用Web API的另一种风格。
猜你喜欢
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
相关资源
最近更新 更多