Adil15
Adil15

Reputation: 435

Blazor httpcontext in helperclass is null

Hello I am following a very helpful guide on adding pagination to blazor from this link: https://www.youtube.com/watch?v=kGvmAeSObsA. My issue is that I have went ahead and made a helper class and a task in it that passes an httpcontext. This is the code code for my helper:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;


namespace TranactionJournalV4.Helpers
{
    public static class HttpContextExtensions
    {
        public static async Task InsertPaginationParameterInResponse<T>(this HttpContext httpContext,
            IQueryable<T> queryable, int recordsPerPage)
        {
            double count = await queryable.CountAsync();
            double pagesQuantity = Math.Ceiling(count / recordsPerPage);
            httpContext.Response.Headers.Add("pagesQuantity", pagesQuantity.ToString());
        }
    }
}

and this is my controller which uses this helper

using TranactionJournalV4.Helpers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TranactionJournalV4.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace TranactionJournalV4.Data
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class SearchService : ControllerBase
    {
        private readonly SqlDbContext context;

        public int Page { get; set; } = 1;

        public SearchService(SqlDbContext context)
        {
            this.context = context;
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<List<TransactionModel>> SearchTransactionsAsync(DateTime transactionDate, [FromQuery] PaginationDTO pagination)
        {

            var queryable = context.TransactionJournal.Where(s => s.TransactionDateTime <= transactionDate).AsQueryable();
            await HttpContext.InsertPaginationParameterInResponse(queryable, pagination.QuantityPerPage);
            return await queryable.Paginate(pagination).ToListAsync();
        }
    }
}

Now when I go through the code everything seems to be going great until it gets to the helper class my httpcontext seems to keep coming up as null. I cannot for the life of me seem to figure out why. Any help would be appreciated. Thanks!

Upvotes: 1

Views: 659

Answers (1)

agua from mars
agua from mars

Reputation: 17404

HttpContext exists only in an http context. This means, if you are not using an http request to call your code you can't get an HttpContext.

A Blazor method doesn't execute in an http context, so HttpContext is null.

Rewrite your extension to be a IQueryable extension returning a page response object such as :

class PageResponse<T>
{
    public int Count { get; set; }
    public IEnumerable<T> Items { get; set; }
}

public static class QueryableExtensions
{
   public static async Task<PageResponse<T>> GetPage<T>(this IQueryable<T> queryable, int skip, int take)
   {
        var count = await queryable.CountAsync().ConfigureAwait(false);
        return new PageResponse<T>
        {
             Count = count,
             Items = await query.Skip(skip).Take(take).ToListAsync().ConfigureAwait(false)
        }
    }
}

Upvotes: 2

Related Questions