相关疑难解决方法(0)

是否必须处理HttpClient和HttpClientHandler?

.NET Framework 4.5中的System.Net.Http.HttpClientSystem.Net.Http.HttpClientHandler实现了IDisposable(通过System.Net.Http.HttpMessageInvoker).

using声明文件说:

通常,当您使用IDisposable对象时,您应该在using语句中声明并实例化它.

这个答案使用了这种模式:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = client.PostAsync("/test", content).Result;
    result.EnsureSuccessStatusCode();
}
Run Code Online (Sandbox Code Playgroud)

但是微软最明显的例子并没有Dispose()明确地或隐含地调用.例如:

c# idisposable using .net-4.5 dotnet-httpclient

315
推荐指数
7
解决办法
12万
查看次数

无法从传输连接读取数据:远程主机强制关闭现有连接

我有一个服务器应用程序,有时,当客户端尝试连接时,我收到以下错误:

在此输入图像描述

注意:"无法从客户端获取流或登录失败"是我在catch语句中添加的文本

它停止的行(sThread:第96行)是:

tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
sr = new StreamReader(clientStream);
sw = new StreamWriter(clientStream);

// line 96:                 
a = sr.ReadLine();
Run Code Online (Sandbox Code Playgroud)

可能是什么导致了这个问题?请注意,它不会一直发生

.net c# ioexception

85
推荐指数
9
解决办法
30万
查看次数

C#HttpClient远程主机强制关闭现有连接

我正在使用其托管页面集成与Alternative Payments进行集成.他们的C#SDK暂时没有这种集成,但正如你所看到的那样非常简单,我发了一个小类来发送post请求并获得JSON响应.

我测试了我在PostMan和cURL上发送的json对象,两者都工作,也是认证头,所以我认为它们不是问题.这是我班级的构造函数:

public AlternativePaymentsCli(string apiSecretKey)
{
    this._apiSecretKey = apiSecretKey;

    _httpClient = new HttpClient();
    _httpClient.DefaultRequestHeaders.Accept
        .Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var authInfo = _apiSecretKey;
    authInfo = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:", _apiSecretKey)));

    // The two line below because I saw in an answer on stackoverflow.
    _httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive"); 
    _httpClient.DefaultRequestHeaders.Add("Keep-Alive", "3600");

    _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Anything.com custom client v1.0");
    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);

}
Run Code Online (Sandbox Code Playgroud)

以及我发布数据的方法:

public string CreateHostedPageTransaction(HostedPageRequest req) 
{
    var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };

    // I send this same json content on …
Run Code Online (Sandbox Code Playgroud)

c# asp.net json dotnet-httpclient

34
推荐指数
3
解决办法
2万
查看次数