Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Async Methods in Action Filters in MVC 5

I'm writing an Action Filter (inheriting from ActionFilterAttribute) which uses HttpClient to POST data to an external server in the OnResultExecuted method. HttpClient has the method PostAsync which returns an awaitable Task<HttpResponseMessage>.

public override void OnResultExecuted(ResultExecutedContext filterContext)
{
    using (var client = new HttpClient())
    {
        var task = client.PostAsync(GetUri(), GetContent());
        var result = task.Result; // blocking
    }
}

The accepted answer to Async action filter in MVC 4 says it is not possible in MVC 4.

Is this still true in MVC 5, and if so what is the best way of calling this asynchronous method without blocking the thread?

like image 342
dav_i Avatar asked Aug 11 '14 14:08

dav_i


1 Answers

Yes, it's still true. Web API 2 has support for async action filters, but MVC 5 still does not. I was just personally frustrated by this not too long ago. For the time being, you will either need to run your async method as sync inside the action filter, or repeat the async code that you would have had in an action filter inside each action that requires it, which you then can run as async.

like image 102
Chris Pratt Avatar answered Sep 23 '22 10:09

Chris Pratt