首页 > 解决方案 > 尝试在 C# 中使用 HttpClient 的现有实例时出现异常

问题描述

更新-通过为 HttpClientHandler 设置代理解决了以下问题。但我仍然想知道第一个请求如何在没有设置代理的情况下成功?为什么只有后续请求(在第一个请求之后)会因为代理而失败?

我有一个简单的类可以在不同的请求中重用“HttpClient”的单个实例。我面临的问题是只有第一次调用成功,而所有后续调用都失败并出现 SocketException。

public class MyHttpClient
 {
    private static readonly HttpClient client;
    static MyHttpClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri("http://x.com");
    }
    public async Task<string> GetSecurityToken(LoginData data)
    {
        var reqMsg = JsonConvert.SerializeObject(data);
        var reqContent = new StringContent(reqMsg, System.Text.Encoding.UTF8, "application/json");
        var response= await client.PostAsync("/api/v1/security/token", reqContent)
        var result = await response.Content.ReadAsStringAsync();
        return result
    }
 }


// The above class is consumed as

        var client = new MyHttpClient();
        var login = new LoginData("abc@gmail.com", "xxxx");
        var result = await client.GetSecurityToken(login); // this call succeeds !
        var result1 = await client.GetSecurityToken(login); // this call fails with an exception, but why?

我在第二次通话中遇到的异常是 - SocketException: A connection attempt failed because the connected party did not proper response after a period of time, or established connection failed because connected host has failed to response

标签: c#dotnet-httpclient

解决方案


推荐阅读