从网页API调用同步外部API [英] Call external api from Web API synchronously

查看:143
本文介绍了从网页API调用同步外部API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我的Web API 2控制器调用外部API,类似这里的要求:

I need to call an external api from my Web API 2 controller, similar to the requirement here:

<一个href=\"http://stackoverflow.com/questions/13222998/calling-external-http-service-using-httpclient-from-a-web-api-action\">Calling使用的HttpClient从Web API行动外部HTTP服务

然而,上述解决方案需要添加异步关键字到我的API方法的GET调用,这样就使我的电话是异步的。我preFER我的API的present客户提供一个同步的方法,但是仍然能够从我自己的调用外部API(并且需要我的API返回前返回)。有没有办法做到这一点?

However, the solution above requires adding the async keyword to my api method's GET call, thus making my call asynchronous. I prefer to present clients of my API with a synchronous method but still be able to call the external api from my own (and will need that to return before my api returns). Is there a way to do this?

推荐答案

禁止上异步操作可能是危险的。它伤害了性能,并可能导致死锁(多在我应该揭露同步包装为异步方法?

Blocking on an async operation could be dangerous. It hurts performance and could lead to deadlocks (more in Should I expose synchronous wrappers for asynchronous methods?)

不过,如果你确定这是你想做的事,这是更好IMO使用 GetAwaiter()调用getResult什么()

But if you're sure that's what you want to do, It's better IMO to use GetAwaiter().GetResult():

using (HttpClient httpClient = new HttpClient())
{
    var response = httpClient.GetAsync(_endpoint).GetAwaiter().GetResult();
    var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    // Do stuff...
}

这是同样的它是否是一个工作任务&LT; T&GT; ,这是同一个呼叫等待转化为(虽然等待任务已完成)和 Task.Result (或 Task.Wait )包装在 AggregateException ,而 GetAwaiter()任何异常。调用getResult ()只抛出了第一个例外等待一样。

It's the same whether it's a Task or Task<T>, it's the same call await translates to (although with await the task already completed) and Task.Result (or Task.Wait) wraps any exceptions in AggregateException while GetAwaiter().GetResult() throws only the first Exception as await does.

这篇关于从网页API调用同步外部API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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