【发布时间】:2016-10-21 15:18:59
【问题描述】:
我的任务是维护一个 C# Web 服务,该服务几乎可以归结为以下与 IIS 8 结合使用的代码:
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// here we process the request and return it after fetching some data
}
}
现在我需要创建另一个 Web 服务,它会请求另一个 Web 服务来获取数据。我收集到的是 C# 中的 HttpClient() 是新的亮点,但是在我的情况下找出如何实现它并不是那么容易(或者这是否是一个好的解决方案)。
我的解决方案类似于
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// make sure that the incoming request is valid
HttpClient client = new HttpClient();
// do stuff with ^client and request the other service
[..]
// return the data from the response from ^client to the first request
}
}
我是在正确的轨道上还是这会是一场灾难?我很乐意接受相关文档的提示或指示。
【问题讨论】:
-
我会重用 HttpClient,每次调用都重新实例化它是非常低效的。
-
@FailedUnitTest 这不是低效的,但如果它被大量使用它可能可能杀死你的服务器。
-
将其设为静态并将其置于 ProcessRequest 方法之外会更好吗?
-
@Steve 如果你使用 async 你不应该有这个问题
-
@Steve 一点也不,
HttpClient是fully re-entrant。
标签: c# web-services dotnet-httpclient