Warm tip: This article is reproduced from stackoverflow.com, please click
c# count odata

How to enable count in OData and .NET Core 3.0 on ASP .NET Application?

发布于 2020-04-20 09:39:07

When I make a request : http://localhost:5000/api/v1/users?$count=true

It returns the object and the values of its properties but it does not return the count of users:

enter image description here

This is my action in the controller:

   /// <summary>
    /// Gets the list of all available users in the system
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [EnableQuery]
    public IEnumerable<UserDto> Get()
    {
        var users = dbContext.Users.ToList();

        return users.Select(u =>
        {
            var dto = mapper.Map<UserDto>(u);
            var claims = dbContext.UserClaims.Where(c => c.UserId == u.Id);
            dto.FirstName = claims.FirstOrDefault(c => c.ClaimType == JwtClaimTypes.GivenName)?.ClaimValue;
            dto.FamilyName = claims.FirstOrDefault(c => c.ClaimType == JwtClaimTypes.FamilyName)?.ClaimValue;
            return dto;
        }).ToList();
    }

This is my startup config:

services.AddOData();

app.UseMvc(router =>
        {
            router.EnableDependencyInjection();
            router.Select().Expand().Filter().OrderBy().MaxTop(100).Count().EnableContinueOnErrorHeader();
            router.MapODataServiceRoute("odata", "odata", GetEdmModel());
        });

    IEdmModel GetEdmModel()
    {
        var odataBuilder = new ODataConventionModelBuilder();
        odataBuilder.EntitySet<IntentUser>("Users");
        return odataBuilder.GetEdmModel();
    }
Questioner
grozdeto
Viewed
23
Ralf Gellrich 2020-02-07 19:49

Since I updated to OData 7.3.0 (and .Net Core 3.1), I have the same Problem.

If you use [Route(...)] and [ApiController] at the controler class, maybe thats the problem. Vanish Route attribute and ApiController attribute: https://stackoverflow.com/a/58849806/12858107