gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:06:29 26 4
gpt4 key购买 nike

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

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

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com