Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.

Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zhougfandCursor committed 2026-05-24 14:17:47 +08:00
commit fa1b286463
241 files changed
+31188

No files matched your search

@@ -0,0 +1,56 @@
using System.Security.Claims;
namespace WmsLite.Api.Infrastructure.Auth;
public sealed class HttpCurrentUserContext : ICurrentUserContext
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HttpCurrentUserContext(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
private ClaimsPrincipal? User => _httpContextAccessor.HttpContext?.User;
public bool IsAuthenticated => User?.Identity?.IsAuthenticated == true;
public string UserId =>
FindClaim(AuthClaimTypes.UserId)
?? FindClaim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Sub)
?? RequireClaim(AuthClaimTypes.UserId);
public string TenantId => RequireClaim(AuthClaimTypes.TenantId);
public string OwnerCode => RequireClaim(AuthClaimTypes.OwnerCode);
public string? DisplayName => User?.FindFirst(AuthClaimTypes.DisplayName)?.Value
?? User?.FindFirst(ClaimTypes.Name)?.Value;
private string? FindClaim(string type) =>
User?.FindFirst(type)?.Value is { Length: > 0 } value ? value.Trim() : null;
private string RequireClaim(string type)
{
if (!IsAuthenticated)
{
throw new UnauthorizedAccessException("User is not authenticated.");
}
var value = User!.FindFirst(type)?.Value;
if (string.IsNullOrWhiteSpace(value))
{
throw new UnauthorizedAccessException($"Missing claim: {type}.");
}
return value.Trim();
}
}
public static class AuthClaimTypes
{
public const string UserId = "sub";
public const string TenantId = "tenant_id";
public const string OwnerCode = "owner_code";
public const string DisplayName = "name";
}
@@ -0,0 +1,14 @@
namespace WmsLite.Api.Infrastructure.Auth;
public interface ICurrentUserContext
{
bool IsAuthenticated { get; }
string UserId { get; }
string TenantId { get; }
string OwnerCode { get; }
string? DisplayName { get; }
}
@@ -0,0 +1,14 @@
namespace WmsLite.Api.Infrastructure.Auth;
public class JwtOptions
{
public const string SectionName = "Jwt";
public string Issuer { get; set; } = "WmsLite";
public string Audience { get; set; } = "WmsLite.Web";
public string Key { get; set; } = string.Empty;
public int ExpiresMinutes { get; set; } = 480;
}
@@ -0,0 +1,52 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using WmsLite.Api.Models;
namespace WmsLite.Api.Infrastructure.Auth;
public interface IJwtTokenService
{
(string Token, DateTime ExpiresAt) CreateToken(SysUser user);
}
public sealed class JwtTokenService : IJwtTokenService
{
private readonly JwtOptions _options;
public JwtTokenService(IOptions<JwtOptions> options)
{
_options = options.Value;
}
public (string Token, DateTime ExpiresAt) CreateToken(SysUser user)
{
if (string.IsNullOrWhiteSpace(_options.Key))
{
throw new InvalidOperationException("Jwt:Key is not configured.");
}
var expires = DateTime.UtcNow.AddMinutes(_options.ExpiresMinutes <= 0 ? 480 : _options.ExpiresMinutes);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(AuthClaimTypes.TenantId, user.TenantId),
new(AuthClaimTypes.OwnerCode, user.OwnerCode),
new(AuthClaimTypes.DisplayName, user.DisplayName ?? user.Username),
new(JwtRegisteredClaimNames.UniqueName, user.Username),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: expires,
signingCredentials: creds);
return (new JwtSecurityTokenHandler().WriteToken(token), expires);
}
}
@@ -0,0 +1,63 @@
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using WmsLite.Api.Common;
using WmsLite.Api.Infrastructure.Auth;
namespace WmsLite.Api.Infrastructure;
public static class AuthServiceCollectionExtensions
{
public static IServiceCollection AddWmsLiteAuth(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<JwtOptions>(configuration.GetSection(JwtOptions.SectionName));
services.AddScoped<ICurrentUserContext, HttpCurrentUserContext>();
services.AddSingleton<IJwtTokenService, JwtTokenService>();
var jwt = configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>() ?? new JwtOptions();
if (string.IsNullOrWhiteSpace(jwt.Key))
{
throw new InvalidOperationException(
"Jwt:Key is not configured. Set Jwt:Key in user-secrets or environment variables.");
}
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// 保留 JWT 原始 claim 名(sub、tenant_id 等),避免映射后 ICurrentUserContext 读不到
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwt.Issuer,
ValidAudience = jwt.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key)),
ClockSkew = TimeSpan.FromMinutes(1),
};
options.Events = new JwtBearerEvents
{
OnChallenge = async context =>
{
context.HandleResponse();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsJsonAsync(
BusinessResult.Fail("Unauthorized.", "401"));
},
};
});
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
return services;
}
}
@@ -0,0 +1,37 @@
namespace WmsLite.Api.Infrastructure;
public static class ConnectionStringConfiguration
{
public const string PostgreSqlName = "PostgreSql";
/// <summary>
/// 读取 PostgreSQL 连接串:环境变量 ConnectionStrings__PostgreSql → Configuration → 校验占位符。
/// </summary>
public static string ResolvePostgreSql(IConfiguration configuration)
{
var fromEnv = Environment.GetEnvironmentVariable($"ConnectionStrings__{PostgreSqlName}");
var connectionString = !string.IsNullOrWhiteSpace(fromEnv)
? fromEnv
: configuration.GetConnectionString(PostgreSqlName);
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new InvalidOperationException(
$"Connection string '{PostgreSqlName}' is not configured. " +
"Use dotnet user-secrets set ConnectionStrings:PostgreSql \"Host=...\" or environment variable ConnectionStrings__PostgreSql.");
}
if (connectionString.Contains("Password=***", StringComparison.OrdinalIgnoreCase)
|| connectionString.Contains("YOUR_PASSWORD", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
$"Connection string '{PostgreSqlName}' contains a placeholder password. " +
"Configure a real password using one of: " +
"dotnet user-secrets set ConnectionStrings:PostgreSql \"Host=...;Password=...\", " +
"environment variable ConnectionStrings__PostgreSql, " +
"or appsettings.Development.local.json (gitignored).");
}
return connectionString;
}
}
@@ -0,0 +1,87 @@
using System.Reflection;
using FluentMigrator.Runner;
using SqlSugar;
namespace WmsLite.Api.Infrastructure;
public static class DatabaseManagementExtensions
{
public static IServiceCollection AddWmsLiteMigrations(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
ValidateDatabaseOptions(options);
services.Configure<DatabaseOptions>(configuration.GetSection(DatabaseOptions.SectionName));
if (!options.Migrations.Enabled)
{
return services;
}
var connectionStringName = string.IsNullOrWhiteSpace(options.Migrations.ConnectionStringName)
? "PostgreSql"
: options.Migrations.ConnectionStringName;
var connectionString = ConnectionStringConfiguration.ResolvePostgreSql(configuration);
services.AddFluentMigratorCore()
.ConfigureRunner(runner => runner
.AddPostgres()
.WithGlobalConnectionString(connectionString)
.ScanIn(typeof(DatabaseManagementExtensions).Assembly).For.Migrations())
.AddLogging(logging => logging.AddFluentMigratorConsole());
return services;
}
public static IApplicationBuilder UseSqlSugarCodeFirst(this WebApplication app)
{
var options = app.Configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
ValidateDatabaseOptions(options);
if (!options.CodeFirst.Enabled)
{
return app;
}
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
var entityTypes = GetSugarTableEntityTypes();
db.CodeFirst.InitTables(entityTypes);
return app;
}
public static IApplicationBuilder UseWmsLiteMigrations(this WebApplication app)
{
var options = app.Configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
ValidateDatabaseOptions(options);
if (!options.Migrations.Enabled)
{
return app;
}
using var scope = app.Services.CreateScope();
var runner = scope.ServiceProvider.GetRequiredService<IMigrationRunner>();
runner.MigrateUp();
return app;
}
private static Type[] GetSugarTableEntityTypes()
{
return typeof(DatabaseManagementExtensions).Assembly
.GetTypes()
.Where(type => type is { IsClass: true, IsAbstract: false }
&& type.GetCustomAttribute<SugarTable>() is not null)
.ToArray();
}
private static void ValidateDatabaseOptions(DatabaseOptions options)
{
if (options.CodeFirst.Enabled && options.Migrations.Enabled)
{
throw new InvalidOperationException("Database CodeFirst and Migrations cannot both be enabled.");
}
}
}
@@ -0,0 +1,22 @@
namespace WmsLite.Api.Infrastructure;
public class DatabaseOptions
{
public const string SectionName = "Database";
public CodeFirstOptions CodeFirst { get; set; } = new();
public MigrationOptions Migrations { get; set; } = new();
}
public class CodeFirstOptions
{
public bool Enabled { get; set; }
}
public class MigrationOptions
{
public bool Enabled { get; set; }
public string ConnectionStringName { get; set; } = "PostgreSql";
}
@@ -0,0 +1,77 @@
using System.Net;
using WmsLite.Api.Common;
namespace WmsLite.Api.Infrastructure;
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionMiddleware> _logger;
public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (BusinessException ex)
{
await WriteResultAsync(context, HttpStatusCode.BadRequest, BusinessResult.Fail(ex.Message, ex.Code));
}
catch (UnauthorizedAccessException ex)
{
await WriteResultAsync(context, HttpStatusCode.Unauthorized, BusinessResult.Fail(ex.Message, "401"));
}
catch (Exception ex) when (IsUniqueConstraintViolation(ex))
{
await WriteResultAsync(
context,
HttpStatusCode.BadRequest,
BusinessResult.BadRequest("数据已存在或违反唯一约束,请更换编码后重试。"));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "Invalid operation.");
await WriteResultAsync(context, HttpStatusCode.InternalServerError, BusinessResult.Fail("服务器内部错误。"));
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled API exception.");
await WriteResultAsync(context, HttpStatusCode.InternalServerError, BusinessResult.Fail("服务器内部错误。"));
}
}
private static bool IsUniqueConstraintViolation(Exception ex)
{
for (var cur = ex; cur is not null; cur = cur.InnerException)
{
var msg = cur.Message;
if (msg.Contains("23505", StringComparison.Ordinal)
|| msg.Contains("duplicate key", StringComparison.OrdinalIgnoreCase)
|| msg.Contains("unique constraint", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private static async Task WriteResultAsync(HttpContext context, HttpStatusCode statusCode, BusinessResult result)
{
if (context.Response.HasStarted)
{
return;
}
context.Response.StatusCode = (int)statusCode;
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsJsonAsync(result);
}
}
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WmsLite.Api.Infrastructure.HttpLogging;
internal static class HttpAccessLogFormatter
{
private const string Bar = "────────────────────────────────────────";
private const string Thick = "════════════════════════════════════════";
public static string Build(
string method,
string? path,
int statusCode,
string requestContent,
string responseContent,
IReadOnlyList<string> sqlStatements)
{
var sb = new StringBuilder(512 + requestContent.Length + responseContent.Length);
sb.AppendLine(Thick);
sb.AppendLine(" HTTP ACCESS");
sb.AppendLine(Thick);
sb.Append("Time : ").AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sb.Append("Method : ").AppendLine(method);
sb.Append("Path : ").AppendLine(path ?? string.Empty);
sb.Append("Status : ").AppendLine(statusCode.ToString());
sb.AppendLine(Bar);
sb.AppendLine("Request");
sb.AppendLine(Bar);
sb.AppendLine(string.IsNullOrEmpty(requestContent) ? "(empty)" : requestContent);
sb.AppendLine();
sb.AppendLine(Bar);
sb.AppendLine("Response");
sb.AppendLine(Bar);
sb.AppendLine(string.IsNullOrEmpty(responseContent) ? "(empty)" : responseContent);
sb.AppendLine();
sb.AppendLine(Bar);
sb.Append("SQL (").Append(sqlStatements.Count).AppendLine(")");
sb.AppendLine(Bar);
if (sqlStatements.Count == 0)
{
sb.AppendLine("(no database commands)");
}
else
{
for (var i = 0; i < sqlStatements.Count; i++)
{
sb.Append('[').Append(i + 1).AppendLine("]");
sb.AppendLine(sqlStatements[i]);
if (i < sqlStatements.Count - 1)
{
sb.AppendLine();
}
}
}
sb.AppendLine(Thick);
return sb.ToString();
}
}
@@ -0,0 +1,27 @@
namespace WmsLite.Api.Infrastructure.HttpLogging;
/// <summary>
/// HTTP 请求/响应日志(中间件)配置。
/// </summary>
public class HttpLoggingOptions
{
public const string SectionName = "HttpLogging";
/// <summary>是否启用中间件记录。</summary>
public bool Enabled { get; set; } = true;
/// <summary>是否将访问信息写入 http_access_log 表(不包含 SQL)。</summary>
public bool PersistToDatabase { get; set; } = true;
/// <summary>
/// 路径(Path)包含任一子串时,将 POST/PUT/PATCH/DELETE 视为「类查询」:不落库、不打印响应体。
/// 默认含分页列表常见片段,与约定「变更类方法记响应」配合使用;空数组表示关闭白名单。
/// </summary>
public string[] PathsOmittingResponseBody { get; set; } = ["paged-list", "pagedlist"];
/// <summary>路径包含任一子串时不记录/不落库请求体(如登录)。</summary>
public string[] PathsOmittingRequestBody { get; set; } = ["/api/Auth/login"];
/// <summary>JSON 日志脱敏字段名(小写比较)。</summary>
public string[] SensitiveFieldNames { get; set; } = ["password", "token", "authorization", "accessToken", "refreshToken"];
}
@@ -0,0 +1,291 @@
using System.Diagnostics;
using System.IO;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WmsLite.Api.Models;
using WmsLite.Api.Repositories.Interfaces;
namespace WmsLite.Api.Infrastructure.HttpLogging;
/// <summary>
/// 记录 HTTP 方法、状态码、请求/响应正文(约定:GET/HEAD/OPTIONS 仅记请求;POST/PUT/PATCH/DELETE 记请求+响应;
/// 路径命中 PathsOmittingResponseBody 时 POST 等也不记响应体)、与 ILogger 格式化日志;可选写入 http_access_log(不含 SQL)。
/// </summary>
public sealed class HttpRequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly HttpLoggingOptions _options;
private readonly ILogger<HttpRequestResponseLoggingMiddleware> _logger;
private readonly IServiceScopeFactory _scopeFactory;
public HttpRequestResponseLoggingMiddleware(
RequestDelegate next,
IOptions<HttpLoggingOptions> options,
ILogger<HttpRequestResponseLoggingMiddleware> logger,
IServiceScopeFactory scopeFactory)
{
_next = next;
_options = options.Value;
_logger = logger;
_scopeFactory = scopeFactory;
}
public async Task InvokeAsync(HttpContext context)
{
if (!_options.Enabled)
{
await _next(context);
return;
}
HttpSqlLogContext.StartRequest(context);
var request = context.Request;
var pathValue = request.Path.Value ?? string.Empty;
var omitRequestBody = ShouldOmitRequestBody(pathValue);
var requestContentRaw = await ReadRequestContentAsync(request);
var requestContent = omitRequestBody
? "(omitted: sensitive path — request body not logged)"
: SanitizeForLog(requestContentRaw);
var sw = Stopwatch.StartNew();
var originalBody = context.Response.Body;
await using var buffer = new MemoryStream();
context.Response.Body = buffer;
try
{
await _next(context);
}
finally
{
sw.Stop();
buffer.Position = 0;
var captureResponse = ShouldCaptureResponseBody(request.Method, pathValue, out var responseOmittedReason);
string responseText;
if (captureResponse)
{
responseText = await ReadStreamAsStringAsync(buffer);
}
else
{
responseText = string.Empty;
}
buffer.Position = 0;
await buffer.CopyToAsync(originalBody);
context.Response.Body = originalBody;
var responseForLog = captureResponse
? SanitizeForLog(responseText)
: responseOmittedReason;
var sql = HttpSqlLogContext.GetSqlSnapshot(context);
var formatted = HttpAccessLogFormatter.Build(
request.Method,
request.Path.Value,
context.Response.StatusCode,
requestContent,
responseForLog,
sql);
_logger.LogInformation("{AccessLog}", formatted);
if (_options.PersistToDatabase)
{
await TryPersistAccessLogAsync(
context,
request,
requestContent,
captureResponse ? responseText : null,
sw.ElapsedMilliseconds,
omitRequestBody);
}
}
}
/// <summary>
/// 约定:GET/HEAD/OPTIONS 只记请求;POST/PUT/PATCH/DELETE 记请求+响应。
/// 例外:路径命中 <see cref="HttpLoggingOptions.PathsOmittingResponseBody"/> 时视为查询型接口,不记响应体。
/// </summary>
private bool ShouldCaptureResponseBody(string method, string pathValue, out string omittedReason)
{
omittedReason = string.Empty;
var m = method.ToUpperInvariant();
if (HttpMethods.IsGet(m) || HttpMethods.IsHead(m) || HttpMethods.IsOptions(m))
{
omittedReason = "(omitted: GET/HEAD/OPTIONS — request only)";
return false;
}
if (m is not ("POST" or "PUT" or "PATCH" or "DELETE"))
{
omittedReason = "(omitted: only POST/PUT/PATCH/DELETE capture response body)";
return false;
}
var keywords = _options.PathsOmittingResponseBody;
if (keywords is { Length: > 0 })
{
foreach (var k in keywords)
{
if (string.IsNullOrWhiteSpace(k))
{
continue;
}
if (pathValue.Contains(k.Trim(), StringComparison.OrdinalIgnoreCase))
{
omittedReason = "(omitted: path matches PathsOmittingResponseBody whitelist)";
return false;
}
}
}
return true;
}
private async Task TryPersistAccessLogAsync(
HttpContext context,
HttpRequest request,
string requestContentForDisplay,
string? responseText,
long elapsedMs,
bool omitRequestBody)
{
try
{
var queryForDb = request.QueryString.HasValue ? request.QueryString.Value : null;
string? bodyForDb;
if (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method) || HttpMethods.IsOptions(request.Method))
{
bodyForDb = null;
}
else
{
bodyForDb = omitRequestBody || string.IsNullOrEmpty(requestContentForDisplay)
? null
: requestContentForDisplay;
}
var entity = new HttpAccessLog
{
TraceId = context.TraceIdentifier,
HttpMethod = request.Method,
Path = request.Path.Value ?? string.Empty,
QueryString = string.IsNullOrEmpty(queryForDb) ? null : queryForDb,
StatusCode = context.Response.StatusCode,
RequestBody = bodyForDb,
ResponseBody = responseText is null || string.IsNullOrEmpty(responseText)
? null
: SanitizeForLog(responseText),
DurationMs = elapsedMs > int.MaxValue ? int.MaxValue : (int)elapsedMs,
ClientIp = GetClientIp(context),
UserId = context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
?? context.User?.FindFirst("sub")?.Value
};
using var scope = _scopeFactory.CreateScope();
var repo = scope.ServiceProvider.GetRequiredService<IHttpAccessLogRepository>();
await repo.InsertAsync(entity);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "写入 http_access_log 失败。");
}
}
private bool ShouldOmitRequestBody(string pathValue)
{
var keywords = _options.PathsOmittingRequestBody;
if (keywords is not { Length: > 0 })
{
return false;
}
foreach (var k in keywords)
{
if (!string.IsNullOrWhiteSpace(k) && pathValue.Contains(k.Trim(), StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private string SanitizeForLog(string? content)
{
if (string.IsNullOrEmpty(content))
{
return string.Empty;
}
var lower = content.ToLowerInvariant();
foreach (var field in _options.SensitiveFieldNames ?? [])
{
if (string.IsNullOrWhiteSpace(field))
{
continue;
}
if (lower.Contains($"\"{field.Trim().ToLowerInvariant()}\"", StringComparison.Ordinal))
{
return "(redacted: sensitive fields)";
}
}
return content;
}
private static string? GetClientIp(HttpContext context)
{
var forwarded = context.Request.Headers["X-Forwarded-For"].ToString();
if (!string.IsNullOrWhiteSpace(forwarded))
{
var first = forwarded.Split(',')[0].Trim();
if (!string.IsNullOrEmpty(first))
{
return first;
}
}
return context.Connection.RemoteIpAddress?.ToString();
}
private static async Task<string> ReadRequestContentAsync(HttpRequest request)
{
if (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method) || HttpMethods.IsOptions(request.Method))
{
return request.QueryString.HasValue ? request.QueryString.Value! : string.Empty;
}
request.EnableBuffering();
request.Body.Position = 0;
using var reader = new StreamReader(
request.Body,
Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
bufferSize: 1024,
leaveOpen: true);
var body = await reader.ReadToEndAsync();
request.Body.Position = 0;
return body;
}
private static async Task<string> ReadStreamAsStringAsync(Stream stream)
{
if (stream.Length == 0)
{
return string.Empty;
}
stream.Position = 0;
using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true);
return await reader.ReadToEndAsync();
}
}
@@ -0,0 +1,57 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
namespace WmsLite.Api.Infrastructure.HttpLogging;
/// <summary>
/// 将当前请求内 SqlSugar 产生的 SQL 收集到 <see cref="HttpContext.Items"/>,供 HTTP 日志合并输出。
/// </summary>
public static class HttpSqlLogContext
{
public const string ItemsKey = "WmsLite.HttpSqlLogBuffer";
public sealed class Buffer
{
private readonly List<string> _sql = new();
private readonly object _gate = new();
public void Append(string sql)
{
if (string.IsNullOrWhiteSpace(sql))
{
return;
}
lock (_gate)
{
_sql.Add(sql.Trim());
}
}
public IReadOnlyList<string> Snapshot()
{
lock (_gate)
{
return _sql.ToArray();
}
}
}
public static void StartRequest(HttpContext context)
{
context.Items[ItemsKey] = new Buffer();
}
public static void Append(HttpContext? context, string executableSql)
{
if (context?.Items[ItemsKey] is Buffer buffer)
{
buffer.Append(executableSql);
}
}
public static IReadOnlyList<string> GetSqlSnapshot(HttpContext context)
{
return context.Items[ItemsKey] is Buffer b ? b.Snapshot() : System.Array.Empty<string>();
}
}
@@ -0,0 +1,59 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using WmsLite.Api.Repositories;
using WmsLite.Api.Repositories.Interfaces;
namespace WmsLite.Api.Infrastructure;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddWmsLiteServices(this IServiceCollection services)
{
services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
services.AddScoped<ITransactionRunner, SqlSugarTransactionRunner>();
services.RegisterByConvention(
typeof(ServiceCollectionExtensions).Assembly,
"WmsLite.Api.Repositories.Interfaces",
"WmsLite.Api.Repositories");
services.RegisterByConvention(
typeof(ServiceCollectionExtensions).Assembly,
"WmsLite.Api.Services.Interfaces",
"WmsLite.Api.Services");
return services;
}
private static IServiceCollection RegisterByConvention(
this IServiceCollection services,
Assembly assembly,
string interfaceNamespace,
string implementationNamespace)
{
var implementationTypes = assembly.GetTypes()
.Where(type => type is { IsClass: true, IsAbstract: false }
&& type.Namespace == implementationNamespace
&& !type.IsNested
&& type.GetCustomAttribute<CompilerGeneratedAttribute>() is null)
.ToDictionary(type => type.Name, StringComparer.Ordinal);
var interfaceTypes = assembly.GetTypes()
.Where(type => type is { IsInterface: true, IsGenericTypeDefinition: false }
&& type.Namespace == interfaceNamespace
&& type.GetCustomAttribute<CompilerGeneratedAttribute>() is null);
foreach (var interfaceType in interfaceTypes)
{
var implementationName = interfaceType.Name.StartsWith('I')
? interfaceType.Name[1..]
: interfaceType.Name;
if (implementationTypes.TryGetValue(implementationName, out var implementationType)
&& interfaceType.IsAssignableFrom(implementationType))
{
services.AddScoped(interfaceType, implementationType);
}
}
return services;
}
}
+100
View File
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using WmsLite.Api.Infrastructure.HttpLogging;
namespace WmsLite.Api.Infrastructure;
public static class SqlSugarSetup
{
public static IServiceCollection AddSqlSugarSetup(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = ConnectionStringConfiguration.ResolvePostgreSql(configuration);
services.AddScoped<ISqlSugarClient>(sp =>
{
var httpContextAccessor = sp.GetRequiredService<IHttpContextAccessor>();
var config = new ConnectionConfig
{
ConnectionString = connectionString,
DbType = DbType.PostgreSQL,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
ConfigureExternalServices = new ConfigureExternalServices
{
EntityService = (property, column) =>
{
if (property.PropertyType == typeof(Dictionary<string, object>)
|| property.PropertyType == typeof(Dictionary<string, string>))
{
column.IsJson = true;
SetJsonbColumnType(column);
}
}
},
AopEvents = new AopEvents
{
OnLogExecuting = (sql, parameters) =>
{
var executable = TryFormatExecutableSql(DbType.PostgreSQL, sql, parameters);
HttpSqlLogContext.Append(httpContextAccessor.HttpContext, executable);
}
}
};
return new SqlSugarClient(config);
});
return services;
}
/// <summary>
/// 生成可在客户端直接执行的 SQL(参数已代入);失败时退回原始 SQL + 参数列表。
/// </summary>
private static string TryFormatExecutableSql(DbType dbType, string sql, SugarParameter[]? parameters)
{
if (string.IsNullOrEmpty(sql))
{
return string.Empty;
}
try
{
return UtilMethods.GetSqlString(dbType, sql, parameters);
}
catch
{
var sb = new StringBuilder();
sb.Append(sql);
if (parameters is { Length: > 0 })
{
sb.AppendLine();
sb.Append("-- params:");
foreach (var p in parameters)
{
sb.Append(' ').Append(p.ParameterName).Append('=').Append(p.Value);
}
}
return sb.ToString();
}
}
private static void SetJsonbColumnType(EntityColumnInfo column)
{
// Different SqlSugar versions expose this property with different names.
const string jsonb = "jsonb";
var columnTypeProperty = column.GetType().GetProperty("ColumnDataType", BindingFlags.Public | BindingFlags.Instance)
?? column.GetType().GetProperty("DataType", BindingFlags.Public | BindingFlags.Instance);
if (columnTypeProperty?.CanWrite == true && columnTypeProperty.PropertyType == typeof(string))
{
columnTypeProperty.SetValue(column, jsonb);
}
}
}
@@ -0,0 +1,43 @@
namespace WmsLite.Api.Infrastructure;
public interface ITransactionRunner
{
Task<T> ExecuteAsync<T>(Func<Task<T>> action);
Task ExecuteAsync(Func<Task> action);
}
public sealed class SqlSugarTransactionRunner : ITransactionRunner
{
private readonly SqlSugar.ISqlSugarClient _db;
public SqlSugarTransactionRunner(SqlSugar.ISqlSugarClient db)
{
_db = db;
}
public async Task<T> ExecuteAsync<T>(Func<Task<T>> action)
{
try
{
_db.Ado.BeginTran();
var result = await action();
_db.Ado.CommitTran();
return result;
}
catch
{
_db.Ado.RollbackTran();
throw;
}
}
public async Task ExecuteAsync(Func<Task> action)
{
await ExecuteAsync(async () =>
{
await action();
return true;
});
}
}