【问题标题】:APIController "Executed" method?APIController“执行”方法?
【发布时间】:2014-10-09 12:27:38
【问题描述】:

ApiController 操作中,我需要在操作完成后立即关闭与数据库的连接。

在控制器下,我覆盖 OnActionExecuted 来完成此操作。

我将如何在 ApiController 操作下完成此操作?

谢谢

【问题讨论】:

    标签: asp.net-web-api asp.net-apicontroller


    【解决方案1】:

    您可以覆盖ExecuteAsync 方法:

    public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
    {
        return base
            .ExecuteAsync(controllerContext, cancellationToken)
            .ContinueWith(t => 
            {
                // the controller action has finished executing, 
                // your custom code could come here ...
    
                return t.Result;
            });
    }
    

    【讨论】:

    • @Darin 在哪里可以找到 filtercontext.Exception?使用 (_session){if (_session == null) 返回;如果(!_session.Transaction.IsActive)返回; if (controllerContext.Request.Exception != null || !ModelState.IsValid) _session.Transaction.Rollback();否则 _session.Transaction.Commit(); }
    • 如果管道中有错误,我不想提交我的事务.... controllerContext.Request.Exception 无效,我在哪里可以获得异常?
    • @Haroon,检查传递给 ContinueWith 匿名方法的 t 参数。你会在那里找到你正在寻找的东西。
    • @DarinDimitrov 谢谢 - 在上面的代码中我不能使用代码返回;编译器错误(返回所需的 HtpResponseMessage)我该怎么办。如果没有异常,我想要我的代码做的就是保存更改...
    • @Haroon,你为什么要退货? API 控制器操作在此阶段已完成执行,您需要做的就是提交或回滚您的事务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    相关资源
    最近更新 更多