从WEB API获取所有用户

时间:2016-01-28 08:12:47

标签: c# web-services asp.net-ajax asp.net-web-api2

我想在返回用户创建的WEB API MVC5项目中创建一个服务。

这有效

[Route("getUsers")]

    // GET: User
    public List<ApplicationUser> getUsers()
    {
        List<ApplicationUser> users = DbContext.Users.ToList();
        return users;
    }

但它返回用户的所有数据,我只对返回FullName和Id感兴趣。

有关如何限制结果的任何建议?

4 个答案:

答案 0 :(得分:2)

三项建议/改进:

  • Web API旨在用于创建RESTful服务。检查您是否使用HTTP/GET调用整个操作,路由本身显示为getXXX。将路线更改为至少/users

  • 不要通过网络返回域对象。您需要实施data-transfer objects。如果几乎没有用例返回用户一个用户,请设计一个只具有这些属性的类。此外,这很重要,因为DbContext返回的对象很重:它们还包含跟踪信息和其他内容,因为它们是对象代理。在序列化和反序列化时,您将避免一些开销和错误。

  • 您的代码应如下所示:DbContext.Users.Select(u => new UserDto { Id = u.ID, Name = u.Name }).ToList()。为了避免手动映射您的对象,我建议您查看AutoMapper库。

  • 设计/实现可在WebAPI中注入/实例化的域层,以封装此复杂性,并让WebAPI调用类似userService.ListUsers()的内容。

答案 1 :(得分:0)

DbContext.Users.ToList()更改为DbContext.Users.Select(u => new ApplicationUser() {ID = u.ID, Name = u.Name}).ToList();

答案 2 :(得分:0)

您甚至不需要使用List,请执行此操作:

[Route("getUsers")]
// GET: User
public IQueryable<object> getUsers()
{
    var users = DbContext.Users.Select( u => new {Id = u.Id, Fullname = u.Fullname});
    return users;
}

如果您没有直接Fullname属性,则可以从FirstnameLastname等其他属性中获取,如下所示:

var users = DbContext.Users.Select( u => new {Id = u.Id, Fullname = u.Firstname + " " + u.Lastname});

答案 3 :(得分:0)

您可以使用IEnumerable的.Select扩展方法来投影数据。 你可以做这样的事情

var users = DbContext.Users(u=> new { Id = u.Id, Fullname = u.Fullname });
return users;