IceTea.Web.Core 1.3.4

dotnet add package IceTea.Web.Core --version 1.3.4
                    
NuGet\Install-Package IceTea.Web.Core -Version 1.3.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="IceTea.Web.Core" Version="1.3.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="IceTea.Web.Core" Version="1.3.4" />
                    
Directory.Packages.props
<PackageReference Include="IceTea.Web.Core" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add IceTea.Web.Core --version 1.3.4
                    
#r "nuget: IceTea.Web.Core, 1.3.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package IceTea.Web.Core@1.3.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=IceTea.Web.Core&version=1.3.4
                    
Install as a Cake Addin
#tool nuget:?package=IceTea.Web.Core&version=1.3.4
                    
Install as a Cake Tool

IceTea.Web.Core (Web 核心组件库)

NuGet版本 GitHub许可证

简介

IceTea.Web.Core 是一个面向 ASP.NET Core 应用程序的核心组件库,提供了仓储模式、依赖注入生命周期管理、Web 扩展方法等功能。该库旨在简化 Web 应用开发,提供标准化的架构模式和便捷的开发工具。

安装

dotnet add package IceTea.Web.Core

核心功能模块

一、仓储模式

IRepository<TEntity> - 基础仓储接口

通用仓储接口,用于标识仓储类型。

IRepository<TEntity, TPrimaryKey> - 泛型仓储接口

提供完整的 CRUD 操作和查询功能的泛型仓储接口。

核心功能:

查询操作
  • IQueryable<TEntity> GetAll() - 获取所有实体的查询对象
  • List<TEntity> GetAllList() - 获取所有实体列表
  • Task<List<TEntity>> GetAllListAsync() - 异步获取所有实体列表
  • List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate) - 条件查询实体列表
  • Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate) - 异步条件查询
  • TEntity Single(Expression<Func<TEntity, bool>> predicate) - 单一实体查询(找不到抛异常)
  • Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> predicate) - 异步单一实体查询
  • TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate) - 第一个匹配实体查询
  • Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate) - 异步第一个匹配查询
插入操作
  • TEntity Insert(TEntity entity) - 插入实体
  • Task<TEntity> InsertAsync(TEntity entity) - 异步插入实体
更新操作
  • TEntity Update(TEntity entity) - 更新实体
  • Task<TEntity> UpdateAsync(TEntity entity) - 异步更新实体
删除操作
  • void Delete(TEntity entity) - 删除实体
  • Task DeleteAsync(TEntity entity) - 异步删除实体
  • void Delete(Expression<Func<TEntity, bool>> predicate) - 条件删除多个实体
  • Task DeleteAsync(Expression<Func<TEntity, bool>> predicate) - 异步条件删除
统计操作
  • int Count() - 获取实体总数
  • Task<int> CountAsync() - 异步获取实体总数
  • int Count(Expression<Func<TEntity, bool>> predicate) - 条件统计
  • Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate) - 异步条件统计
  • long LongCount() - 获取长整型实体总数
  • Task<long> LongCountAsync() - 异步获取长整型实体总数
  • long LongCount(Expression<Func<TEntity, bool>> predicate) - 长整型条件统计
  • Task<long> LongCountAsync(Expression<Func<TEntity, bool>> predicate) - 异步长整型条件统计

二、依赖注入生命周期接口

IScoped - 作用域生命周期标记接口

标记需要注册为 Scoped 生命周期的服务。

ISingleton - 单例生命周期标记接口

标记需要注册为 Singleton 生命周期的服务。

ITransient - 瞬态生命周期标记接口

标记需要注册为 Transient 生命周期的服务。

三、服务发现

IExposedServiceTypesProvider - 服务类型提供者接口

用于自动发现和注册服务类型。

四、Web扩展方法

提供 ASP.NET Core 相关的扩展方法:

1. HttpContext扩展
  • 请求上下文相关的便捷方法
  • 用户身份认证扩展
  • 响应处理扩展
2. IServiceCollection扩展
  • 自动服务注册
  • 配置绑定扩展
  • 中间件注册扩展
3. IApplicationBuilder扩展
  • 管道配置扩展
  • 错误处理扩展
  • 路由配置扩展

使用指南

1. 仓储模式使用示例

// 定义实体
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public bool IsActive { get; set; }
}

// 实现仓储接口
public class ProductRepository : IRepository<Product, int>
{
    private readonly DbContext _context;
    
    public ProductRepository(DbContext context)
    {
        _context = context;
    }
    
    public IQueryable<Product> GetAll() => _context.Set<Product>();
    
    public List<Product> GetAllList() => _context.Set<Product>().ToList();
    
    public async Task<List<Product>> GetAllListAsync() 
        => await _context.Set<Product>().ToListAsync();
    
    public List<Product> GetAllList(Expression<Func<Product, bool>> predicate)
        => _context.Set<Product>().Where(predicate).ToList();
    
    public async Task<List<Product>> GetAllListAsync(Expression<Func<Product, bool>> predicate)
        => await _context.Set<Product>().Where(predicate).ToListAsync();
    
    // 实现其他接口方法...
}

// 在Startup中注册
services.AddScoped<IRepository<Product, int>, ProductRepository>();

2. 依赖注入生命周期使用示例

// Scoped 服务
public class UserService : IScoped
{
    public async Task<User> GetUserByIdAsync(int id)
    {
        // 实现用户查询逻辑
    }
}

// Singleton 服务
public class CacheService : ISingleton
{
    private readonly MemoryCache _cache = new();
    
    public T Get<T>(string key) => _cache.Get<T>(key);
    public void Set<T>(string key, T value) => _cache.Set(key, value);
}

// Transient 服务
public class EmailService : ITransient
{
    public async Task SendEmailAsync(string to, string subject, string body)
    {
        // 实现邮件发送逻辑
    }
}

// 自动注册服务
services.AutoRegisterServices(typeof(UserService).Assembly);

3. Web扩展方法使用示例

// Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
    // 自动注册控制器和服务
    services.AddControllersWithViews();
    
    // 自动注册标记接口的服务
    services.AutoRegisterServices(Assembly.GetExecutingAssembly());
    
    // 配置选项绑定
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    
    // 添加自定义中间件
    services.AddCustomMiddleware();
}

// Startup.Configure
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    // 使用自定义错误处理
    app.UseCustomExceptionHandler();
    
    // 配置路由
    app.UseCustomRouting();
    
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

4. HTTP上下文扩展使用示例

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly IUserService _userService;
    
    public UserController(IUserService userService)
    {
        _userService = userService;
    }
    
    [HttpGet("{id}")]
    public async Task<IActionResult> GetUser(int id)
    {
        // 使用扩展方法获取用户IP
        var userIp = HttpContext.GetUserIp();
        
        // 使用扩展方法检查是否AJAX请求
        if (HttpContext.IsAjaxRequest())
        {
            // 返回JSON格式
            var user = await _userService.GetUserByIdAsync(id);
            return Ok(user);
        }
        
        // 返回视图
        return View();
    }
    
    [HttpPost]
    public async Task<IActionResult> CreateUser([FromBody] CreateUserDto dto)
    {
        // 验证模型
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState.GetErrors());
        }
        
        var user = await _userService.CreateUserAsync(dto);
        return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
    }
}

技术特性

架构模式

  • 仓储模式: 标准化的数据访问层抽象
  • 依赖注入: 完整的DI生命周期管理
  • 关注点分离: 业务逻辑与数据访问解耦
  • 可测试性: 易于单元测试的设计

性能优化

  • 延迟加载: IQueryable 支持延迟执行
  • 异步操作: 全异步API设计
  • 连接管理: 高效的数据库连接管理
  • 缓存友好: 支持缓存策略集成

安全特性

  • 参数化查询: 防止SQL注入攻击
  • 权限验证: 集成ASP.NET Core认证授权
  • 数据验证: 模型验证和业务规则验证
  • 日志记录: 完整的操作日志记录

典型应用场景

  1. RESTful API: 构建标准化的Web API服务
  2. 企业应用: 大型企业级Web应用开发
  3. 微服务: 微服务架构的应用程序
  4. CMS系统: 内容管理系统开发
  5. 电商网站: 电子商务平台开发

最佳实践

1. 仓储模式最佳实践

public interface IProductRepository : IRepository<Product, int>
{
    Task<List<Product>> GetActiveProductsAsync();
    Task<decimal> GetAveragePriceAsync();
    Task<PagedResult<Product>> GetPagedProductsAsync(int page, int pageSize);
}

public class ProductRepository : IProductRepository
{
    private readonly ApplicationDbContext _context;
    
    public ProductRepository(ApplicationDbContext context)
    {
        _context = context;
    }
    
    public async Task<List<Product>> GetActiveProductsAsync()
    {
        return await GetAllListAsync(p => p.IsActive);
    }
    
    public async Task<decimal> GetAveragePriceAsync()
    {
        return await GetAll()
            .Where(p => p.IsActive)
            .AverageAsync(p => p.Price);
    }
    
    public async Task<PagedResult<Product>> GetPagedProductsAsync(int page, int pageSize)
    {
        var query = GetAll().Where(p => p.IsActive);
        var totalCount = await query.CountAsync();
        var items = await query
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();
            
        return new PagedResult<Product>
        {
            Items = items,
            TotalCount = totalCount,
            Page = page,
            PageSize = pageSize
        };
    }
}

2. 服务层最佳实践

public class ProductService : IScoped
{
    private readonly IProductRepository _productRepository;
    private readonly ILogger<ProductService> _logger;
    
    public ProductService(
        IProductRepository productRepository,
        ILogger<ProductService> logger)
    {
        _productRepository = productRepository;
        _logger = logger;
    }
    
    public async Task<ProductDto> GetProductAsync(int id)
    {
        var product = await _productRepository.FirstOrDefaultAsync(p => p.Id == id);
        if (product == null)
        {
            throw new EntityNotFoundException($"Product with id {id} not found");
        }
        
        return MapToDto(product);
    }
    
    public async Task<ProductDto> CreateProductAsync(CreateProductDto dto)
    {
        // 业务验证
        await ValidateProductAsync(dto);
        
        var product = new Product
        {
            Name = dto.Name,
            Price = dto.Price,
            IsActive = true,
            CreatedAt = DateTime.UtcNow
        };
        
        var createdProduct = await _productRepository.InsertAsync(product);
        await _productRepository.SaveChangesAsync();
        
        _logger.LogInformation("Product created: {ProductId}", createdProduct.Id);
        
        return MapToDto(createdProduct);
    }
}

3. 控制器最佳实践

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;
    
    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
    
    [HttpGet]
    [AllowAnonymous]
    public async Task<ActionResult<PagedResult<ProductDto>>> GetProducts(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 10)
    {
        var products = await _productService.GetPagedProductsAsync(page, pageSize);
        return Ok(products);
    }
    
    [HttpGet("{id:int}")]
    [AllowAnonymous]
    public async Task<ActionResult<ProductDto>> GetProduct(int id)
    {
        try
        {
            var product = await _productService.GetProductAsync(id);
            return Ok(product);
        }
        catch (EntityNotFoundException)
        {
            return NotFound();
        }
    }
    
    [HttpPost]
    [Authorize(Roles = "Admin")]
    public async Task<ActionResult<ProductDto>> CreateProduct([FromBody] CreateProductDto dto)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        
        var product = await _productService.CreateProductAsync(dto);
        return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
    }
}

配置说明

依赖注入配置

// Program.cs 或 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // 自动注册所有标记接口的服务
    services.AutoRegisterServices(Assembly.GetExecutingAssembly());
    
    // 手动注册特定服务
    services.AddScoped<IProductService, ProductService>();
    services.AddSingleton<ICacheService, RedisCacheService>();
    services.AddTransient<IEmailService, SmtpEmailService>();
    
    // 配置选项
    services.Configure<DatabaseOptions>(Configuration.GetSection("Database"));
    services.Configure<JwtOptions>(Configuration.GetSection("Jwt"));
}

中间件配置

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 全局异常处理
    app.UseGlobalExceptionHandler();
    
    // 请求日志记录
    app.UseRequestLogging();
    
    // 身份认证
    app.UseAuthentication();
    app.UseAuthorization();
    
    // 自定义中间件
    app.UseCustomMiddleware();
    
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

依赖说明

  • Microsoft.AspNetCore.Mvc.Core: ASP.NET Core MVC 核心组件
  • Microsoft.EntityFrameworkCore: Entity Framework Core
  • Microsoft.Extensions.DependencyInjection: 依赖注入扩展
  • IceTea.Pure: 基础工具类库

兼容性

  • .NET版本: .NET 6.0+
  • ASP.NET Core: 6.0+
  • Entity Framework: EF Core 6.0+
  • 操作系统: Windows, Linux, macOS

许可证

MIT License

作者

WuMing

贡献

欢迎提交 Issue 和 Pull Request!

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.4 106 8/2/2026
1.3.3 101 7/31/2026
1.3.2 100 7/30/2026
1.3.1 107 7/27/2026
1.3.0 115 6/16/2026
1.2.0 109 6/11/2026
1.0.25 375 11/17/2025
1.0.24 299 8/25/2025
1.0.23 127 8/23/2025
1.0.22 294 8/7/2025
1.0.21 224 5/27/2025
1.0.20 157 3/14/2025
1.0.19 193 12/20/2024
1.0.17 225 9/17/2024
1.0.15 172 9/3/2024
1.0.14 197 8/11/2024
1.0.13 156 7/31/2024
1.0.12 213 6/26/2024
1.0.11 209 5/31/2024
Loading failed