4

In an ApiController action I need to close a connection to a database as soon as the action is finished executing.

Under a controller I override OnActionExecuted to accomplish this.

How would I accomplish this under an ApiController action?

Thanks

Mrchief
  • 75,126
  • 20
  • 142
  • 189
Leo
  • 900
  • 1
  • 11
  • 26

1 Answers1

7

You could override the ExecuteAsync method:

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;
        });
}
Mrchief
  • 75,126
  • 20
  • 142
  • 189
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • @Darin where can I find the filtercontext.Exception? using (_session){if (_session == null) return; if (!_session.Transaction.IsActive) return; if (controllerContext.Request.Exception != null || !ModelState.IsValid) _session.Transaction.Rollback(); else _session.Transaction.Commit(); } – Haroon Jul 05 '13 at 09:06
  • I dont want to commit my transaction if there is an error in the pipelines.... controllerContext.Request.Exception is invalid, where can I get hold of the Exception? – Haroon Jul 05 '13 at 09:07
  • @Haroon, inspect the `t` argument that is passed to the `ContinueWith` anonymous method. You will find what you are looking there. – Darin Dimitrov Jul 05 '13 at 09:09
  • @DarinDimitrov thanks - in the code above I cannot use the code return; compiler error (return a HtpResponseMessage required) what would I do. All I want my code to do is save changes if there are no exceptions... – Haroon Jul 05 '13 at 09:11
  • @Haroon, why do you want to return anything? The API controller action has finished executing at this stage and all you need to do is commit or rollback your transaction. – Darin Dimitrov Jul 05 '13 at 10:24
  • I found this very usefull! – L.Trabacchin Nov 28 '13 at 10:02