refactor: 完成系统基础架构重构与业务逻辑优化

本次提交包含多项核心变更:
1.  **用户体系重构**:将管理员用户状态从字符串改为整型枚举,移除微信用户冗余字段Points和GrowthPoints,新增通用基础实体主键配置
2.  **代码清理**:删除HealthController、WxUserMedal、WxUserBag等废弃文件,移除WeChatDto中冗余查询字段
3.  **响应格式统一**:重构BaseResponse与ResultCode枚举,标准化全局响应格式
4.  **权限与验证优化**:添加JWT认证与开发环境免认证逻辑,新增模型验证过滤器,统一控制器认证配置
5.  **工具与配置更新**:新增dotnet-tools.json配置EF工具,调整Swagger与压缩中间件配置,优化SqlSugar默认值处理逻辑
6.  **业务逻辑简化**:移除AutoMapper映射,改为手动映射DTO以提升性能,修复异常处理与响应返回逻辑
This commit is contained in:
glz
2026-06-02 17:58:10 +08:00
parent 8ed012bba8
commit 0a32754740
24 changed files with 551 additions and 209 deletions

View File

@ -8,6 +8,7 @@ using QYZH.InteractiveMagazine.Models.Enum;
namespace QYZH.InteractiveMagazine.WebApi.Controllers;
[Route("api/[controller]")]
[ApiController]
public class AdminController : BaseController
@ -63,7 +64,7 @@ public class AdminController : BaseController
var userId = GetCurrentUserId();
if (userId == null)
{
return BaseResponse<AdminUserInfoOutput>.Fail("未获取到用户信息", 401);
return BaseResponse<AdminUserInfoOutput>.Fail(ResultCode.DENY, "未获取到用户信息");
}
var result = await _adminAuthService.GetAdminInfoAsync(userId.Value);
@ -104,12 +105,12 @@ public class AdminController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "创建管理员业务异常: {Message}", ex.Message);
return BaseResponse<AdminUserOutput>.Fail(ex.Message, ex.Code);
return BaseResponse<AdminUserOutput>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "创建管理员系统异常,参数:{Input}", input);
return BaseResponse<AdminUserOutput>.Fail("创建管理员失败,请稍后重试", 500);
return BaseResponse<AdminUserOutput>.Fail("创建管理员失败,请稍后重试");
}
}
@ -130,12 +131,12 @@ public class AdminController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "更新管理员业务异常: {Message}", ex.Message);
return BaseResponse<AdminUserOutput>.Fail(ex.Message, ex.Code);
return BaseResponse<AdminUserOutput>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "更新管理员系统异常ID{Id},参数:{Input}", id, input);
return BaseResponse<AdminUserOutput>.Fail("更新管理员失败,请稍后重试", 500);
return BaseResponse<AdminUserOutput>.Fail("更新管理员失败,请稍后重试");
}
}
@ -155,12 +156,12 @@ public class AdminController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "删除管理员业务异常: {Message}", ex.Message);
return BaseResponse<object>.Fail(ex.Message, ex.Code);
return BaseResponse<object>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "删除管理员系统异常ID{Id}", id);
return BaseResponse<object>.Fail("删除管理员失败,请稍后重试", 500);
return BaseResponse<object>.Fail("删除管理员失败,请稍后重试");
}
}
@ -180,12 +181,12 @@ public class AdminController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "获取管理员业务异常: {Message}", ex.Message);
return BaseResponse<AdminUserOutput>.Fail(ex.Message, ex.Code);
return BaseResponse<AdminUserOutput>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "获取管理员系统异常ID{Id}", id);
return BaseResponse<AdminUserOutput>.Fail("获取管理员信息失败,请稍后重试", 500);
return BaseResponse<AdminUserOutput>.Fail("获取管理员信息失败,请稍后重试");
}
}
@ -205,12 +206,12 @@ public class AdminController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "查询管理员列表业务异常: {Message}", ex.Message);
return BaseResponse<PageListModel<AdminUserOutput>>.Fail(ex.Message, ex.Code);
return BaseResponse<PageListModel<AdminUserOutput>>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "查询管理员列表系统异常,参数:{Input}", input);
return BaseResponse<PageListModel<AdminUserOutput>>.Fail("查询管理员列表失败,请稍后重试", 500);
return BaseResponse<PageListModel<AdminUserOutput>>.Fail("查询管理员列表失败,请稍后重试");
}
}
}

View File

@ -1,12 +1,15 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using QYZH.InteractiveMagazine.Models.Dto;
using QYZH.InteractiveMagazine.Models.Enum;
using System.Security.Claims;
namespace QYZH.InteractiveMagazine.WebApi.Controllers;
/// <summary>
/// 基础控制器
/// </summary>
[Authorize]
[ApiController]
[Route("api/[controller]")]
[ApiExplorerSettings(GroupName = nameof(ApiVersionEnum.Platform))]
@ -18,7 +21,7 @@ public abstract class BaseController : ControllerBase
/// <returns>用户ID</returns>
protected long? GetCurrentUserId()
{
var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == "userId");
var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
if (userIdClaim != null && long.TryParse(userIdClaim.Value, out var userId))
{
return userId;
@ -32,7 +35,7 @@ public abstract class BaseController : ControllerBase
/// <returns>用户名</returns>
protected string? GetCurrentUserName()
{
return User.Claims.FirstOrDefault(c => c.Type == "userName")?.Value;
return User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
}
/// <summary>
@ -55,6 +58,6 @@ public abstract class BaseController : ControllerBase
/// <returns>统一响应对象</returns>
protected BaseResponse<object> Fail(string message, int code = 500)
{
return BaseResponse<object>.Fail(message, code);
return BaseResponse<object>.Fail(ResultCode.GLOBAL_ERROR, message);
}
}

View File

@ -1,22 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using QYZH.InteractiveMagazine.Models.Dto;
namespace QYZH.InteractiveMagazine.WebApi.Controllers;
/// <summary>
/// 健康检查控制器
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class HealthController : BaseController
{
/// <summary>
/// 健康检查
/// </summary>
/// <returns>pong</returns>
[HttpGet("ping")]
public BaseResponse<string> Ping()
{
return Success("pong");
}
}

View File

@ -6,6 +6,9 @@ using QYZH.InteractiveMagazine.Models.Dto;
namespace QYZH.InteractiveMagazine.WebApi.Controllers;
/// <summary>
/// 微信用户控制器
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class WxUserController : BaseController
@ -19,6 +22,11 @@ public class WxUserController : BaseController
_logger = logger;
}
/// <summary>
/// 创建微信用户
/// </summary>
/// <param name="input">创建微信用户输入参数</param>
/// <returns>创建的微信用户输出参数</returns>
[HttpPost("users")]
public async Task<BaseResponse<WxUserOutput>> CreateUserAsync([FromBody] WxUserInput input)
{
@ -30,15 +38,21 @@ public class WxUserController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "创建微信用户业务异常: {Message}", ex.Message);
return BaseResponse<WxUserOutput>.Fail(ex.Message, ex.Code);
return BaseResponse<WxUserOutput>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "创建微信用户系统异常,参数:{Input}", input);
return BaseResponse<WxUserOutput>.Fail("创建微信用户失败,请稍后重试", 500);
return BaseResponse<WxUserOutput>.Fail("创建微信用户失败,请稍后重试");
}
}
/// <summary>
/// 更新微信用户
/// </summary>
/// <param name="id">微信用户ID</param>
/// <param name="input">更新微信用户输入参数</param>
/// <returns>更新的微信用户输出参数</returns>
[HttpPut("users/{id}")]
public async Task<BaseResponse<WxUserOutput>> UpdateUserAsync(long id, [FromBody] WxUserInput input)
{
@ -50,15 +64,19 @@ public class WxUserController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "更新微信用户业务异常: {Message}", ex.Message);
return BaseResponse<WxUserOutput>.Fail(ex.Message, ex.Code);
return BaseResponse<WxUserOutput>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "更新微信用户系统异常ID{Id},参数:{Input}", id, input);
return BaseResponse<WxUserOutput>.Fail("更新微信用户失败,请稍后重试", 500);
return BaseResponse<WxUserOutput>.Fail("更新微信用户失败,请稍后重试");
}
}
/// <summary>
/// 删除微信用户
/// </summary>
/// <param name="id">微信用户ID</param>
/// <returns>删除的微信用户输出参数</returns>
[HttpDelete("users/{id}")]
public async Task<BaseResponse<object>> DeleteUserAsync(long id)
{
@ -70,15 +88,19 @@ public class WxUserController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "删除微信用户业务异常: {Message}", ex.Message);
return BaseResponse<object>.Fail(ex.Message, ex.Code);
return BaseResponse<object>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "删除微信用户系统异常ID{Id}", id);
return BaseResponse<object>.Fail("删除微信用户失败,请稍后重试", 500);
return BaseResponse<object>.Fail("删除微信用户失败,请稍后重试");
}
}
/// <summary>
/// 获取微信用户信息
/// </summary>
/// <param name="id">微信用户ID</param>
/// <returns>微信用户信息输出参数</returns>
[HttpGet("users/{id}")]
public async Task<BaseResponse<WxUserOutput>> GetUserByIdAsync(long id)
{
@ -90,15 +112,19 @@ public class WxUserController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "获取微信用户业务异常: {Message}", ex.Message);
return BaseResponse<WxUserOutput>.Fail(ex.Message, ex.Code);
return BaseResponse<WxUserOutput>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "获取微信用户系统异常ID{Id}", id);
return BaseResponse<WxUserOutput>.Fail("获取微信用户信息失败,请稍后重试", 500);
return BaseResponse<WxUserOutput>.Fail("获取微信用户信息失败,请稍后重试");
}
}
/// <summary>
/// 获取微信用户列表
/// </summary>
/// <param name="input">查询微信用户列表输入参数</param>
/// <returns>微信用户列表输出参数</returns>
[HttpPost("users/list")]
public async Task<BaseResponse<PageListModel<WxUserOutput>>> GetUsersListAsync([FromBody] WxUserQueryInput input)
{
@ -110,12 +136,12 @@ public class WxUserController : BaseController
catch (BusinessException ex)
{
_logger.LogWarning(ex, "查询微信用户列表业务异常: {Message}", ex.Message);
return BaseResponse<PageListModel<WxUserOutput>>.Fail(ex.Message, ex.Code);
return BaseResponse<PageListModel<WxUserOutput>>.Fail(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "查询微信用户列表系统异常,参数:{Input}", input);
return BaseResponse<PageListModel<WxUserOutput>>.Fail("查询微信用户列表失败,请稍后重试", 500);
return BaseResponse<PageListModel<WxUserOutput>>.Fail("查询微信用户列表失败,请稍后重试");
}
}
}

View File

@ -2,7 +2,9 @@ using Autofac;
using Autofac.Extensions.DependencyInjection;
using BCrypt.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.OpenApi;
using Microsoft.OpenApi.Models;
using QYZH.InteractiveMagazine.Common.Extensions;
using QYZH.InteractiveMagazine.Common.Helpers;
using QYZH.InteractiveMagazine.Infrastructure.Autofacs;
@ -46,9 +48,12 @@ builder.Host.UseSerilog();
builder.Services.AddControllers(options =>
{
options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;//Required 不作为必填
options.Filters.Add<ModelValidActionFilterAttribute>();//添加自定义模型验证
})
.AddJsonOptions(options =>
{
// 配置 JSON 不区分大小写(支持 camelCase 和 PascalCase
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
// 配置返回时间格式转换
options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeConverter());
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
@ -94,7 +99,20 @@ builder.Services.AddSwaggerGen(option =>
BearerFormat = "JWT",
Scheme = "Bearer"
});
option.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
// 过滤文档/路径/方法筛选接口的响应结果
option.DocInclusionPredicate((docName, apiDesc) =>
@ -112,7 +130,7 @@ builder.Services.AddSwaggerGen(option =>
});
});
builder.Services.AddInfrastructureServices(builder.Configuration);
builder.Services.AddInfrastructureServices(builder.Configuration, builder.Environment);
//注册 HttpContextAccessor
builder.Services.AddHttpContextAccessor();
@ -128,7 +146,30 @@ builder.Services.AddCors(options =>
.AllowAnyHeader();
});
});
#region
// 1.首先配置压缩选项的Options>
builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = System.IO.Compression.CompressionLevel.Optimal;
});
builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = System.IO.Compression.CompressionLevel.Fastest;
});
// 2.在服务容器中注册响应压缩服务
builder.Services.AddResponseCompression(options =>
{
// 可以在这里进行详细配置
options.EnableForHttps = true; // 启用对HTTPS响应的压缩请注意安全风险
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
//指定哪些类型的响应应该被压缩。默认列表包含常见的文本类类型,如 text/html, text/css, application/javascript, application/json, text/plain等
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(["image/svg+xml", "application/json", "text/plain"]);
});
#endregion
var app = builder.Build();
{
@ -143,6 +184,7 @@ var app = builder.Build();
c.DocExpansion(DocExpansion.None); // ->修改界面打开时自动折叠
});
}
app.UseServiceContext();
app.UseHttpsRedirection();
app.UseCors("AllowAll");

View File

@ -11,8 +11,7 @@
<PackageReference Include="Autofac" Version="9.1.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="11.0.0" />
<PackageReference Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.27" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "10.0.8",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}