filter - 如何为事务管理编写自定义过滤器

标签 filter transactions asp.net-core asp.net-core-mvc entity-framework-core

我想使用过滤器来管理具有以下要求的事务。

  • 过滤器必须紧跟在 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/

    相关文章:

    google-analytics - 将自定义指标添加到谷歌分析交易

    c# - identityServer4收到token后应该如何添加redis?

    ios - iOS 中的谷歌地图有过滤器

    javascript - 向这个 jquery 添加第二个函数?

    c - LabWindows 中的实时数据过滤?

    entity-framework - 在 Entity Framework Core 中的其他上下文中加载属性

    asp.net-core - 如何在 cPanel 中托管 ASP.Net Core API?

    c++ - boost::filter_iterator——我将如何使用 STL 做到这一点?

    Spring rabbitMQ - 事务和事务管理器

    java - @Transactional 在 Spring Boot 中不起作用