异步调用方法在行动过滤器在MVC 5 [英] Calling Async Methods in Action Filters in MVC 5

查看:337
本文介绍了异步调用方法在行动过滤器在MVC 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个Action过滤器,它使用的HttpClient 来POST数据到外部(从 ActionFilterAttribute 继承)服务器在 OnResultExecuted 方法。 的HttpClient 的方法 PostAsync 返回一个awaitable 任务< Htt的presponseMessage>

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
    }
}

接受的答案异步操作筛选器在MVC 4 说,这是在MVC 4.不可能

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

这是MVC中仍然5真,如果是的话是什么调用这个异步方法,而不会阻塞线程的最佳方式?

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

推荐答案

是的,它仍然是真实的。网页API 2具有异步操作筛选器的支持,但MVC 5仍然没有。我只是个人不受此受挫不是很久以前。暂时,你要么需要运行异步方法的同步动作过滤器内部,或重复异步code,你将不得不在每一个动作内的动作过滤器需要它,你那么的可以的运行是​​异步。

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.

这篇关于异步调用方法在行动过滤器在MVC 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆