标签: dotnet-httpclient

引发给定异常时无法让 Polly 重试 Http 调用

我的服务定义:

var host = new HostBuilder().ConfigureServices(services =>
{
    services
        .AddHttpClient<Downloader>()
        .AddPolicyHandler((services, request) =>
            HttpPolicyExtensions
            .HandleTransientHttpError()
            .Or<SocketException>()
            .Or<HttpRequestException>()
            .WaitAndRetryAsync(
                new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10) },
                onRetry: (outcome, timespan, retryAttempt, context) =>
                {
                    Console.WriteLine($"Delaying {timespan}, retrying {retryAttempt}.");
                }));

    services.AddTransient<Downloader>();

}).Build();
Run Code Online (Sandbox Code Playgroud)

实施Downloader

class Downloader
{
    private HttpClient _client;
    public Downloader(IHttpClientFactory factory)
    {
        _client = factory.CreateClient();
    }

    public Download()
    {
        await _client.GetAsync(new Uri("localhost:8800")); // A port that no application is listening
    }
}
Run Code Online (Sandbox Code Playgroud)

通过此设置,我预计会看到三次尝试查询端点,并将日志消息打印到控制台(我也尝试使用记录器但未成功,为简单起见,这里使用控制台)。

我看到的是未处理的异常消息(我只希望在重试和打印日志后看到),而不是调试消息。

未处理的异常:System.Net.Http.HttpRequestException:无法建立连接,因为目标计算机主动拒绝它。(127.0.0.1:8800) ---> System.Net.Sockets.SocketException (10061): 无法建立连接,因为目标计算机主动拒绝连接。

c# dependency-injection dotnet-httpclient polly httpclientfactory

3
推荐指数
1
解决办法
2405
查看次数

使用 HTTPCLient 下载文件时减少内存占用

我想知道是否有一种方法可以避免获取所有缓冲区,然后使用 HttpClient 和 File.WriteAllBytes 将它们写入文件。

这是我使用的代码片段

public async Task<byte[]> DownloadAsByteArray(string filename)
{
    _logger.LogDebug($"Start downloading {filename} file at {DateTime.Now}");
    
    var result = await _httpClient.GetByteArrayAsync(filename);
    
    return result;
}
Run Code Online (Sandbox Code Playgroud)
var bytes = await _downloadFileService.DownloadAsByteArray(fileDownload);

await File.WriteAllBytesAsync(fullFlePathName, bytes);
Run Code Online (Sandbox Code Playgroud)

对于相当大的文件,应用程序内存增长得非常快。

.net c# stream async-await dotnet-httpclient

3
推荐指数
1
解决办法
1257
查看次数

.NET 6 在 Web API 项目控制器中使用 HTTP 客户端进行 API 调用

我对 .NET 还很陌生,并且一直在使用HttpClientAPI 控制器中调用其他 API。根据这篇文章,我应该只有一个HttpClient实例,因为它会导致套接字耗尽错误。

不过,我目前正在HttpClient为每个 API 控制器创建一个。我应该创建一个static包含单个实用程序类HttpClient,还是应该保留我所拥有的?使用本身调用其他 API 的 API 控制器时,是否有更好的替代方案或最佳实践?

如果需要更多信息,请告诉我。

c# asp.net-web-api dotnet-httpclient .net-core asp.net-core

3
推荐指数
1
解决办法
7538
查看次数

Polly 创建没有 ServiceCollection 的 HttpClient (IHttpClientBuilder.AddPolicyHandler)

我正在尝试使用 的IHttpClientBuilder.AddPolicyHandler方法Microsoft.Extensions.Http.Polly创建内置 Polly 策略的 HttpClient 实例。但是,我没有使用 IoC 和 ServiceCollection。如何IHttpClientBuilder在没有 ServiceCollection 和 IoC 的情况下创建,以便我可以使用扩展方法AddPolicyHandler。即使我有 的实例IHttpClientBuilder,如何创建 HttpClient?

c# dependency-injection dotnet-httpclient polly .net-7.0

3
推荐指数
1
解决办法
425
查看次数

新的HttpClient代理设置问题

我正在尝试根据新的fw 4.5功能重写旧的网络身份验证逻辑,例如HttpClient和await/async,我在请求和响应之间遇到意外的延迟(大约15秒).我的猜测是因为客户端尝试从IE中查找/使用代理,就像使用旧的HttpRequest/WebClient一样.这是代码:

public static async Task<AuthResult> GetDataFromServiceAsync(string url, string login, string password)
{
     Debug.WriteLine("[" + DateTime.Now + "] GetDataFromServiceAsync");
     var handler = new HttpClientHandler { Credentials = new NetworkCredential(login, password)/*, UseProxy = false*/ };
     var client = new HttpClient(handler) { MaxResponseContentBufferSize = Int32.MaxValue };
     try
     {
         var resp = await client.GetAsync(new Uri(url));
         var content = resp.Content.ReadAsStringAsync().Result;
         var auth = ParseContent(content);
         Debug.WriteLine("[" + DateTime.Now + "] Returning AuthResult : " + auth);
         return new AuthResult { Success = auth, Exception = …
Run Code Online (Sandbox Code Playgroud)

.net networking async-await .net-4.5 dotnet-httpclient

2
推荐指数
1
解决办法
7417
查看次数

如何从HttpRequestException获取JSON错误消息

我有一种情况,我必须HttpResponseMessage在一个catch语句中提取一个Response(),但我认为不能完成(await在catch中使用).此外,如果我在捕获后执行此操作,则HttpResponseMessage消息将显示为"已处置".码:

 private async void MakeHttpClientPostRequest()
 {
     HttpResponseMessage response = null;
     try
     {
         HttpClient httpClient = new HttpClient();
         httpClient.Timeout = TimeSpan.FromSeconds(15);
         HttpContent httpContent = null;
         if (postJSON != null)
         {
             httpContent = new StringContent(postJSON);
             httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
         }

         response = await httpClient.PostAsync(url, httpContent);
         if (response != null)
         {
             response.EnsureSuccessStatusCode();
             netResults = await response.Content.ReadAsStringAsync();
         }

         if (this.convertedType != null)
         {
             MemoryStream assetReader = GetMemoryStreamFromString(netResults);
             assetReader.Position = 0;
             object value = fromJSON(assetReader, this.convertedType);
             networkReqSuccessWithObjectCallback(this, …
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient

2
推荐指数
1
解决办法
8994
查看次数

在CookieContainer.Add期间c# - CookieException,部分cookie无效

我有一个需要与服务器通话的Windows Phone 8应用程序.HttpClient当我在服务器上调用登录服务(位于子目录"/ authentication"下)时,服务器将cookie设置为我的客户端处理程序.然后我把Cookie它拿出来存放在IsolatedStorageSettings.当我关闭并重新打开我的应用程序,从而重新实例化我的HttpClient,我想获得CookieIsolatedStorageSettings,它手动设置为我的客户端处理程序.但是,我得到一条CookieException消息:"Cookie的'Domain'='mobile.some-domain.com'部分无效."

我为此写的代码如下:

public static void saveCookies()
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    var cookies = handler.CookieContainer.GetCookies(new Uri(ROOT + "/authentication"));
    settings["sessionCookie"] = cookies["JSESSIONID"];
    settings.Save();
}

public static bool checkCookies()
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    if (settings.Contains("sessionCookie"))
    {
        Cookie c = settings["sessionCookie"] as Cookie;
        Uri uri = new Uri(ROOT + "/authentication");
        handler.CookieContainer.Add(uri, c);
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

ROOT是" https://mobile.some-domain.com/ERSMobileApps/services ",处理程序的类型是HttpClientHandler.

我是第一次处理cookie,所以对此有任何帮助/评论将不胜感激.提前致谢.

c# cookies dotnet-httpclient

2
推荐指数
1
解决办法
7702
查看次数

为什么我的C#AJAX请求使用HTTP并且使用HTTPS失败?

我有一个与django-allauth合作的django应用程序.

我还在生产环境中使用HTTPS部署了它.

来自Web浏览器的AJAX查询指向HTTPS站点,使用POST登录到'/ accounts/login /'按预期返回JSON.

问题在于我的C#移动代码(基于Xamarin).

_client = new HttpClient(handler) {BaseAddress = uri};
_client.DefaultRequestHeaders.Add("X_REQUESTED_WITH", "XMLHttpRequest");
Run Code Online (Sandbox Code Playgroud)

当用作BaseAddress的'uri'是http并指向我的开发服务器时,一切正常,我在响应中得到了JSON.

但是,当uri指向我的https站点(坐在nginx和gunicorn后面)时,我得到了一个HTML响应.

不知道为什么会这样.有人有任何想法吗?

c# django nginx dotnet-httpclient django-allauth

2
推荐指数
1
解决办法
309
查看次数

不能使用Asp MVC 6 Web Api的HttpClient

我尝试编写简单的代码:

 public async Task<string> GetData(String labelName)
    {           
        using (var client = new HttpClient())
        {
            var uri = new Uri(@"https://example.com/over/search_field?=search_label=" + labelName);

            var response = await client.GetAsync(uri).ConfigureAwait(false);
            var textResult = await response.Content.ReadAsStringAsync();
            return textResult;
        }
    }
Run Code Online (Sandbox Code Playgroud)

在project.json:

 {
"webroot": "wwwroot",
"version": "1.0.0-*",
"dependencies": {
  "Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",
 "Microsoft.AspNet.Mvc": "6.0.0-beta8",
 "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
 "Microsoft.AspNet.StaticFiles": "1.0.0-beta8",

 "Microsoft.Framework.Logging": "1.0.0-beta8",
 "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
 "Microsoft.Framework.Logging.Debug": "1.0.0-beta8",
 "Microsoft.Net.Http": "2.2.22"
  },      
 "frameworks": {
  "dnx451": {
    "dependencies": {
       "Microsoft.AspNet.WebApi.Client": "5.2.3",
      "Microsoft.AspNet.WebApi.Owin": "5.2.3",
      "System.Net.Http": "4.0.1-beta-23409"


   },
   "frameworkAssemblies": {
     "System.Net": "4.0.0.0",
     "System.Net.Http": "4.0.0.0"
   } …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc dotnet-httpclient asp.net-core-mvc

2
推荐指数
1
解决办法
1501
查看次数

为HttpClient Post方法准备Json Object

我试图为Post方法准备一个Json有效负载.服务器无法解析我的数据.我的值上的ToString()方法不能正确地将它转换为Json,请你建议正确的方法.

  var values = new Dictionary<string, string> 
                {
                  {"type", "a"}, {"card", "2"}
                };
  var data = new StringContent(values.ToSttring(), Encoding.UTF8, "application/json");
  HttpClient client = new HttpClient();
  var response = client.PostAsync(myUrl, data).Result;
  using (HttpContent content = response.content) 
  {
      result = response.content.ReadAsStringAsync().Result;
  }
Run Code Online (Sandbox Code Playgroud)

c# json http-post json.net dotnet-httpclient

2
推荐指数
1
解决办法
6712
查看次数