简体   繁体   English

从 Web API 同步调用外部 api

[英]Call external api from Web API synchronously

I need to call an external api from my Web API 2 controller, similar to the requirement here:我需要从我的 Web API 2 控制器调用外部 api,类似于这里的要求:

Calling external HTTP service using HttpClient from a Web API Action 使用 HttpClient 从 Web API 操作调用外部 HTTP 服务

However, the solution above requires adding the async keyword to my api method's GET call, thus making my call asynchronous.但是,上面的解决方案需要在我的 api 方法的 GET 调用中添加async关键字,从而使我的调用异步。 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).我更喜欢使用同步方法向我的 API 的客户端呈现,但仍然能够从我自己的调用外部 api(并且需要在我的 api 返回之前返回)。 Is there a way to do this?有没有办法做到这一点?

Blocking on an async operation could be dangerous.阻塞async操作可能很危险。 It hurts performance and could lead to deadlocks (more in Should I expose synchronous wrappers for asynchronous methods? )它会损害性能并可能导致死锁(更多信息请参见我应该为异步方法公开同步包装器吗?

But if you're sure that's what you want to do, It's better IMO to use GetAwaiter().GetResult() :但是,如果您确定这就是您想要做的,IMO 最好使用GetAwaiter().GetResult()

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

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.无论是Task还是Task<T>都是一样的,它是相同的调用await转换为(尽管await任务已经完成)并且Task.Result (或Task.Wait )在GetAwaiter().GetResult()时将任何异常包装在AggregateException GetAwaiter().GetResult()await一样只抛出第一个Exception

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM