This commit is contained in:
owenchen committed 2026-05-19 09:52:24 +08:00
1 parent 4d946d9dfc
commit 13d3047102
5 files changed
+64 -38

No files matched your search

@@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Mvc.Filters;
using CloudBuilder.Core.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -10,7 +12,8 @@ using System.Transactions;
namespace CloudBuilder.Core.DatabaseAccessor
{
/*
事务范围不匹配:TransactionScope 管理的是分布式事务,但对于单个数据库连接,通常不需要分布式事务。
事务范围:TransactionScopeOption.RequiresNew 管理的是分布式事务,
TransactionScopeOption.Required但对于单个数据库连接,通常不需要分布式事务。
OnActionExecutionAsync 是 ASP.NET Core 中异步的 Action 过滤器执行方法。
// OnActionExecuting: Action 执行前
[开始事务]
@@ -19,6 +22,7 @@ namespace CloudBuilder.Core.DatabaseAccessor
↓
// OnActionExecuted: Action 执行后(无论是否异常)
[检查异常]
//Controller对象不抛出异常,返回的是异常对象ValidatedException、ServiceErrorException(方便前端信息统一处理)
[提交或回滚事务]
*/
[AttributeUsage(AttributeTargets.Method)]
@@ -38,15 +42,59 @@ namespace CloudBuilder.Core.DatabaseAccessor
base.OnActionExecuting(context);
}
//public override void OnActionExecuting(ActionExecutingContext context)
//{
// // 正确:单机数据库事务(不是分布式)
// _transactionScope = new TransactionScope(
// TransactionScopeOption.Required,
// new TransactionOptions
// {
// IsolationLevel = IsolationLevel.ReadCommitted
// },
// TransactionScopeAsyncFlowOption.Enabled); // 必须加这个
// base.OnActionExecuting(context);
//}
public override void OnActionExecuted(ActionExecutedContext context)
{
if (_transactionScope != null)
if (_transactionScope == null)
{
if (context.Exception == null)
base.OnActionExecuted(context);
return;
}
bool needRollback = false;
try
{
// ==============================================
// 核心逻辑:判断返回值是不是异常对象
// ==============================================
if (context.Result is ObjectResult objectResult)
{
var value = objectResult.Value;
if (value != null)
{
// 只要是这两个异常 → 必须回滚
if (value is ValidatedException || value is ServiceErrorException)
{
needRollback = true;
}
}
}
// 如果没有异常,才提交
if (!needRollback)
{
//必须要有 SaveChanges() 调用,否则数据只会停留在内存中,不会真正保存到数据库。
_transactionScope.Complete();
}
}
finally
{
// 不 Complete() 就是自动回滚
_transactionScope.Dispose();
}