我想使用过滤器来管理具有以下要求的事务。
Authorization Filter
之后执行( 我不想用
order
明确)执行操作方法后回滚。
我认为过滤器实现如下所示:
private IDbContextTransaction _tx;
private readonly MyDbContext _dbContext;
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
_tx = _dbContext.Database.BeginTransaction();
}
public override void OnActionExecuted(ActionExecutedContext context)
{
if (context.Exception == null)
{
_tx.Commit();
}
else
{
_tx.Rollback();
}
}
然后我想将它用于如下命令操作:
[HttpPost]
[Command]
public IActionResult Create([FromBody] CreateTodoCommand cmd)
{
}
根据文档:
Resource filters are the first filter to handle a request after authorization, and the last one to touch the request as it is leaving the filter pipeline. They’re especially useful to implement caching or otherwise short-circuit the filter pipeline for performance reasons.
在我的情况下使用似乎可行。如果没有其他解决方案,我将采用此方法。另一方面,我想尝试编写自己的自定义过滤器类型,例如
Authorization Filter
并将其放入过滤器管道中。问题:如何实现自定义过滤器?
最佳答案
您可以创建自定义属性并将其设置为您的操作。
using Microsoft.AspNetCore.Mvc.Filters;
public class CustomActionFilter: Attribute, IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
}
}
关于filter - 如何为事务管理编写自定义过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38345955/