. Net Core 3 Web API с OData $ count не возвращает значение - PullRequest
0 голосов
/ 10 июля 2020

У меня есть рабочий веб-API, который отвечает на запрос GET и возвращает список отчетов. Недавно я реализовал Odata и такие параметры, как $ filter и $ top, когда я использую $ count, похоже, что они игнорируются.

Я прочитал несколько блогов и форм, но мне не удалось заставить его работать.

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; private set; }

   

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

                
        services.AddMvc(o =>
        {
            o.ReturnHttpNotAcceptable = true;
            o.EnableEndpointRouting = false;
        });
        

        // Connection string from environmental variables
        var connectionString = Configuration["connectionString:077test"];

        // Connection to SQL
        services.AddDbContext<ServiceCatalogContext>(option => option.UseSqlServer(connectionString));

        // Scope 
        services.AddScoped<IReportsRepo, ReportsRepo>();


        services.AddControllers();


        services.AddOData();

        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler(appBuilder =>
            {
                appBuilder.Run(async context =>
                {
                    context.Response.StatusCode = 500;
                    await context.Response.WriteAsync("An unexpected fault happened. Try again later.");
                });
            });
        }


        //app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();
       
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
           
        });
       
        app.UseStatusCodePages();
        //app.UseMvc();
        //expanding app.UseMvc for oData            
        app.UseMvc(routeBuilder =>
        {
            //routeBuilder.EnableDependencyInjection();
            routeBuilder.Select()
                        .OrderBy()
                        .Filter()
                        .SkipToken()
                        .MaxTop(10)
                        .Expand()
                        .Count();
            routeBuilder.MapODataServiceRoute("api", "api", GetEdmModel());
        });
        
       
    }

    private static IEdmModel GetEdmModel()
    {
        var odataBuilder = new ODataConventionModelBuilder();
        odataBuilder.EntitySet<ReportsDto>("reports");

        return odataBuilder.GetEdmModel();
    }

    
}

ReportsController.cs

 public class ReportsController : ODataController     //Controller //ControllerBase
{
    private readonly IReportsRepo _reportsRepo;

    public ReportsController(IReportsRepo reportsRepo, IMapper mapper)
    {
        _reportsRepo = reportsRepo ??
              throw new ArgumentNullException(nameof(reportsRepo));  //handle if resultsRepo is null
    }

    [HttpGet]
    [EnableQuery()] //enabled OData querying
    [ODataRoute("reports")]
    public ActionResult<IQueryable<ReportsDto>> GetReports()    //updated from IEnumerable to IQueryable when OData was added
    {
        var results = _reportsRepo.GetReports();

        //return Ok(_mapper.Map<IEnumerable<ReportsDto>>(results));   //mapper not working with OData if I change IEnumerable to IQueryable
        return Ok(results);

    }
}

API возвращает результаты, и я могу использовать $ filter и $ top, но я просто не могу понять, как чтобы заставить $ count работать.

Любая помощь с моими спецификациями c API будет принята с благодарностью!

...