I am having difficulty overriding the OnActionExecutedAsync
method of the ActionFilterAttribute
in a WebApi project. So far I have the following c# code
public class MyFilter : ActionFilterAttribute
{
public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionContext, CancellationToken cancellationToken)
{
var response = await MyAsyncMethod();
if(response.SomeProperty)
DoThing();
}
}
However when debugging the code, the response to the await method never returns. This is true for any async method as I have tested a few I know to be working elsewhere in my code base. I tried void methods too, as well as using .Wait()
and .Result
all having the same issue.
var response = MyAsyncMethod().Result;
await MyVoidAsyncMethod();
MyVoidAsyncMethod().Wait(cancellationToken);
So I think the issue is with awaiting any method inside the OnActionExecutedAsync method.
I noticed I can await the base method without an issue though.
await base.OnActionExecutedAsync(actionContext, cancellationToken);
How can I call an async method inside the OnActionExecutedAsync
method?
Update with example showing purely awaited methods
As a resolution in the comments was suggested by making sure all methods in the chain are awaited I have added an example that shows only awaited methods that still causes the issue.
public class MyFilter : ActionFilterAttribute
{
public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionContext, CancellationToken cancellationToken)
{
await base.OnActionExecutedAsync(actionContext, cancellationToken);
await DefinitelyAllAsync();
}
private async Task DefinitelyAllAsync()
{
var request = WebRequest.Create("http://www.stackoverflow.com");
var response = await Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null) as HttpWebResponse;
Debug.Assert(response?.StatusCode == HttpStatusCode.OK);
}
}
This never reaches the Debug.Assert
.