Calling Async Methods in Action Filters in MVC 5

丶灬走出姿态 提交于 2019-12-09 15:01:08

问题


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?


回答1:


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.




回答2:


Some guy kind of 'back ported' it here

https://github.com/jdaigle/Hydrogen.Extensions.Mvc5

I haven't tried it and can't recommend it but if you're in transition to .NET Core it might be worth considering. Fortunately I managed to remove all async code from my extension - this time.



来源:https://stackoverflow.com/questions/25246030/calling-async-methods-in-action-filters-in-mvc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!