C#MVC返回Request.CreateResponse返回项目和显示在视图中的列表

时间:2016-11-21 00:48:04

标签: c# asp.net-mvc asp.net-web-api

如何使用返回请求返回项目列表。 我的代码:

public class UserController : BaseController
{
    [Route("current")]
    public HttpResponseMessage GetCurrent(int version)
    {
        ValidateApiVersionAndState(version);
        return Request.CreateResponse(HttpStatusCode.OK, new { Email = "Something@gmail.com", FirstName = "Some", LastName = "thing", DateOfBirth = new DateTime(1990, 9, 6), MontlySalary = "50000.00" });

        //var UserModel = new List<UserDB>();
        //UserModel.Add(new UserDB { Id = 1, Email = "something@gmail.com", FirstName = "Some", LastName = "Thing", DateOfBirth = new DateTime(1990, 9, 6), MonthlySalary = 50000.00 });
        //UserModel.Add(new UserDB { Id = 1, Email = "Steve@gmail.com", FirstName = "Steve", LastName = "Wonder", DateOfBirth = new DateTime(1984, 8, 4), MonthlySalary = 100000.00 });
        //return Request.CreateResponse(HttpStatusCode.OK, new { UserModel });

    }
}

1 个答案:

答案 0 :(得分:1)

创建一个新的List<object>() { ...your objects here }并将其传递给回复。

public class UserController : BaseController {
    [Route("current")]
    public HttpResponseMessage GetCurrent(int version) {
        ValidateApiVersionAndState(version);
        var result = new List<object>() {
            new { Email = "Something@gmail.com", FirstName = "Some", LastName = "thing", DateOfBirth = new DateTime(1990, 9, 6), MontlySalary = "50000.00" },
            new { Email = "Steve@gmail.com", FirstName = "Steve", LastName = "Wonder", DateOfBirth = new DateTime(1984, 8, 4), MonthlySalary = 100000.00 }
        );

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