Can an OData controller return an Excel?

Viewed 20

Using ASP.Net Core 6. OData V4 (Nuget 8.0.10). EF Core 6. Blazor WASM client.

When an ODATA query from my client application hits the back end API, it ALWAYS sends its ODATA query to the IQueryable Get() end point / method as below. It uses generics to allow just about any entity/table to be queried.

As you can imagine, the ODATA middleware does a great job of intercepting these requests, converting the ODATA query into something that EF Core can interpret and then returns the result set as JSON back to the client.

ATM the client application always displays the result set in a data grid for the user. However, rather than have ODATA (or whatever is that does it) return the data as JSON, I'd like to create and return an XLSX file instead.

How might I go about this? I can't determine when or where ODATA applies its query in order to produce a result set based on the ODATA query that the client fired in. Is there some middleware I can tap into? Any pointers would be nice! I do not need help with XLSX file creation itself.

Thank you.

Controller:

    [ApiController]
    [Route("api/[controller]")]
    public class GenericBaseController<T> : ODataController where T : BaseEntity
    {

        private readonly IGenericRepositoryServer<T> crud;

        public GenericBaseController(IGenericRepositoryServer<T> _crud)
        {
            crud = _crud;
        }


        [HttpGet("Post")]
        public virtual IQueryable<T> Get()
        {
            return crud.Query().AsNoTracking();
        }
...

Startup.cs. ConfigureServices:

...
                services.AddControllers()
                .AddOData(opt => opt.AddRouteComponents("odata", MyDBContext.GetEdmModel())
                .Count()
                .Select()
                .Filter()
                .Expand()
                .OrderBy()
                .SkipToken()
                );
...

And Configure in Startup.cs:

public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
                app.UseODataRouteDebug();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();
            app.UseODataQueryRequest();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });


        }
0 Answers
Related