HttpClient问题,如何重用不同的URI?

时间:2018-03-20 12:45:46

标签: c# asp.net-core asp.net-core-2.0 dotnet-httpclient

我在Azure(app服务)上托管了一个简单的webapp,它可以调用两个不同的外部API。昨天我们有一个巨大的预期流量高峰,整个事情崩溃了,我现在意识到是因为我正在创建和处理HttpClient的新实例,如下所示:

var url = "https://www.externalapi.com/someendpoint" +
    "/takethedata.js?" +
    "[form]email=" + visitor.EmailAddress +
    "&[form]name=" + visitor.FirstName + " " + visitor.LastName +
    "&[form]zip=" + visitor.zip +
    "&[form]location=" + city + ", " + state;

using(var handler = new HttpClientHandler())
{
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
    handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 |
        System.Security.Authentication.SslProtocols.Tls11 |
        System.Security.Authentication.SslProtocols.Tls;

    using(var client = new HttpClient(handler))
    {
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = await client.GetAsync(url);

    }
}

在另一种方法的同一个控制器中,我以相同的方式制作另一个外部API:

string AuthToken = "2678c7b5-3cvt-XXXX-XXXX-XXXXXXXXX";
string BaseUrl = "https://someotherdomain.com/dosomething/" + AuthToken;

var jsonContent = "{ \"param1\": \"" + value1 + "\", \"Timeout\":\"15\", \"Verbose\":\"True\" }";

using(var client = new HttpClient())
{
    client.BaseAddress = new Uri(BaseUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = await client.PostAsync(BaseUrl,
        new StringContent(jsonContent, Encoding.UTF8, "application/json"));

    if (!response.IsSuccessStatusCode)
    {
        return Json("Email Check Error");
    }
    else
    {
        var responseContent = await response.Content.ReadAsStringAsync();

        return Json(responseContent);
    }
}

我一直在阅读HttpClient并为每个外部API创建一个单例?设置不同的URI等问题,我真的很困惑如何继续。如果我只是转储“使用”它可能会解决?如果我需要创建一个单例,那么在哪里可以演示如何执行此操作并将其应用于我的场景?谢谢!

1 个答案:

答案 0 :(得分:3)

你到底想要做什么?如果我理解正确,你只想在不同的URI上使用相同的HttpClient发出另一个请求,这是正确的吗?

在这种情况下,您可以使用HttpClient对象调用相应的请求函数,例如(GET请求):

HttpResponseMessage response = await client.GetAsync(url);

尝试在构造函数中初始化客户端对象,如果您认为每次发送请求时重新实例化它都会继续使用相同的实例吗?