0

Let me prefix first that there are already two questions from Stack Overflow with accepted answers that async action filters are not supported:

Async action filter in MVC 4
Calling Async Methods in Action Filters in MVC 5

So, I'm looking for a 'work-around'. This is what I currently do in my WebApi application:

public class MessageLoggingHandler : DelegatingHandler
{

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        await LogRequestInfo(request);
        var response = await base.SendAsync(request, cancellationToken);
        await LogResponseInfo(response);
        return response;
    }

What I am trying to achieve is to log the request and log the response as a cross cutting concern. How can I do this in MVC? Is it even possible? I see two posts with a possible solution... has anyone used it? Does it work? Should I even go down this path? Are there alternatives? I'm really hesitant to adopt either approach for fear of breaking something in our application.

1) Implement a custom AsyncControllerActionInvoker
http://ayende.com/blog/163170/building-async-unit-of-work-with-mvc-4

2) Create and Async Controller Base Class, uses the "ParallelExtensionsExtras" library (whatever that is), and overrides some of the BeginExecute, EndExecute methods.
Perform Async operation asp.net mvc outside of the action

Community
  • 1
  • 1
Raymond
  • 3,382
  • 5
  • 43
  • 67
  • 2
    ASP.NET vNext *will* support async filters on its version of MVC. So, another option is to just log synchronously for now (inefficient, but it works), and then upgrade to a proper async filter when ASP.NET vNext comes out. – Stephen Cleary Sep 12 '14 at 23:24
  • When you say do it synchronously, do you mean that I have to change my controller methods to be synchronous too? All our action methods are async at the moment, and I don't want to be telling the team to re-write all the code to make it synchronous again with threads to call the async code. – Raymond Sep 15 '14 at 23:51
  • 1
    No, you can just make the `Log*Info` methods called from the filter synchronous; the controller methods can stay asynchronous. – Stephen Cleary Sep 16 '14 at 00:01
  • I've recently [published a library](https://www.nuget.org/packages/Hydrogen.Extensions.Mvc5.Async) that adds proper support for async filters (heavily based on code in from [ASP.NET MVC Core](https://github.com/aspnet/Mvc)). Source is also available here: https://github.com/jdaigle/Hydrogen.Extensions.Mvc5. – Joseph Daigle Mar 21 '17 at 02:36

0 Answers0