helperclass 中的 Blazor httpcontext 为空

Blazor httpcontext in helperclass is null

您好,我正在按照一个非常有用的指南向 blazor 添加分页,来自 link:https://www.youtube.com/watch?v=kGvmAeSObsA。我的问题是我已经做了一个助手 class 和一个传递 httpcontext 的任务。这是我的助手的代码:

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());
        }
    }
}

这是我使用这个助手的控制器

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();
        }
    }
}

现在,当我检查代码时,一切似乎都很顺利,直到它到达助手 class 我的 httpcontext 似乎一直显示为 null。我无法为我的生活似乎弄清楚为什么。任何帮助,将不胜感激。谢谢!

HttpContext 仅存在于 http 上下文中。这意味着,如果您没有使用 http 请求来调用您的代码,您将无法获得 HttpContext

Blazor 方法不在 http 上下文中执行,因此 HttpContext 为空。

将您的扩展重写为 IQueryable 返回页面响应对象的扩展,例如:

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)
        }
    }
}