首页 > 解决方案 > 在 ASMX WebService 中使用 HttpClient

问题描述

在我的 asmx Web 服务中,我必须从另一个 Web 服务调用方法。因为 asmx webService 不处理 async/await,所以我的代码如下所示:

public string switchRelay(int TermId)
{
    string result = "-1";
    string request = "...";
    client.DefaultRequestHeaders.Add("SOAPAction", "...");

    var content = new StringContent(request, Encoding.UTF8, "text/xml");
    using (var response = client.PostAsync(ConfigurationManager.AppSettings["Url"], content))
    {
        response.Wait();
        var soapResponse = response.Result.Content.ReadAsStringAsync();
        soapResponse.Wait();
        var soap = XDocument.Parse(soapResponse.Result, LoadOptions.PreserveWhitespace);
        soapResponse.Dispose();
        result = soap.Descendants().ToList()[3].Value;
    }
    return result;
}

我的问题是,我应该在哪里创建 HttpClient 的实例。现在我将它创建为全局服务变量,但这会随着每个请求运行,所以它每次都会创建新的 httpClient(我试图将它用作单例,但它看起来在 asmx WebService 中是不可能的)。可以在 WebMethod 中创建新的 HttpClient 实例吗?

谢谢任何建议。

标签: c#asp.netasmxdotnet-httpclient

解决方案


推荐阅读