小编Pet*_*ala的帖子

类型化 HttpClient 与 IHttpClientFactory

以下两种设置 HttpClient 的场景有什么区别吗?

我应该选择其中一种而不是另一种吗?

键入的客户端:

public class CatalogService 
{
    private readonly HttpClient _httpClient;
    
    public CatalogService(HttpClient httpClient) {
        _httpClient = httpClient;
    }
    
    public async Task<string> Get() {
        var response = await _httpClient.GetAsync();
        ....
    }
    
    public async Task Post() {
        var response = await _httpClient.PostAsync();
        ...
    }
}
// Startup.cs
//Add http client services at ConfigureServices(IServiceCollection services)
services.AddHttpClient<ICatalogService, CatalogService>();
Run Code Online (Sandbox Code Playgroud)

IHttpClientFactory:

public class CatalogService 
{
    private readonly IHttpClientFactory _factory;
    
    public CatalogService(IHttpClientFactory factory) {
        _factory = factory;
    }
    
    public async Task<string> Get() {
        var …
Run Code Online (Sandbox Code Playgroud)

c# async-await dotnet-httpclient asp.net-core httpclientfactory

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

HttpGetAttribute 构造函数中的“name”属性是什么?

当我使用HttpGet(...)时,智能感知告诉我,除了第一个参数(即pattern )之外,我还有nameorder。虽然后者对我来说是显而易见的,但我有点不确定参数名称的用途

转到文档,我看到HttpGet的构造函数仅声明一个参数。这让我很困惑,我怀疑我错过了一些东西,或者使用了框架的版本而不是核心,或者其他东西。

c# routes http-get .net-core asp.net-core

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

无法从字符串转换为 NewtonSoft.Json.JsonReader

我是 Xamarin Forms 的新手,我正在尝试创建一种从 API 请求项目列表的方法。但是,由于错误消息,我无法编译解决方案

行中的“无法从字符串转换为 NewtonSoft.Json.JsonReader” var Items = JsonSerializer.Deserialize<Dictionary<string, Paises>>(content);

这是整个例程:

public static async Task<List<Paises>> GetPaisesActivosAsync()
{
    string baseUri = new BaseUri().baseUri;
    string sufixUri = "/PaisesApi/GetActives";
    var uri = baseUri + sufixUri;

    List<Paises> listaPaisesActivos = null;

    HttpResponseMessage response = await client.GetAsync(uri);
    if (response.IsSuccessStatusCode)
    {
        string content = await response.Content.ReadAsStringAsync();
        var Items = JsonSerializer.Deserialize<Dictionary<string, Paises>>(content);
    }
    return listaPaisesActivos;
}    
Run Code Online (Sandbox Code Playgroud)

预先感谢您的支持。

问候,

c# jsonserializer xamarin.forms asp.net-core-webapi

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

Asp.Net 5/Core app.UseExceptionHandler() 不工作

我在启动时有

(更新:解决方案是将 UseRouting 移到 /api/error 路由下)

app.UseRouting();

if (env.IsDevelopment()) {               
    app.UseExceptionHandler("/api/error/error-local-development"); 
    SwaggerConfig.Configure(app);              
}
else {             
    app.UseExceptionHandler("/api/error/error");
}

 app.UseCors();
 app.UseHttpsRedirection();
 app.UseDefaultFiles();
 app.UseSpaStaticFiles(); 
 app.UseAuthentication();
 app.UseAuthorization();
 app.UseRequestLocalization(options);
  app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ResultHub>("/hubs/resultHub");
            });


            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "wwwroot";
            });

Run Code Online (Sandbox Code Playgroud)

但是,throw new Exception()在控制器操作中时,永远不会调用错误控制器方法。

[Route("api/error")]
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorController : OwnBaseController
{
    public ErrorController(IApplicationUserService applicationUserService, ILogger<ErrorController> logger, IDiagnosticContext diagnosticContext) : base(applicationUserService, logger, diagnosticContext)
    {
    }

    [Route("error")]
    public IActionResult Error()
    {
        return Problem(); 
    }

    [Route("error-local-development")]
    public IActionResult ErrorLocalDevelopment([FromServices] IWebHostEnvironment webHostEnvironment) …
Run Code Online (Sandbox Code Playgroud)

c# error-handling asp.net-core asp.net5

13
推荐指数
1
解决办法
1万
查看次数

使用 Polly 和指定客户端刷新令牌

我有一个看起来像这样的政策

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(resp => resp.StatusCode == HttpStatusCode.Unauthorized)
    .WaitAndRetryAsync(3, 
        retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
        onRetry: (resp, timeSpan, context) =>
        {
            // not sure what to put here
        });
Run Code Online (Sandbox Code Playgroud)

然后我有一个指定的客户端,看起来像这样

services.AddHttpClient("MyClient", client =>
    {
        client.BaseAddress = new Uri("http://some-url.com");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
        client.Timeout = 30000;
    })
    .AddPolicyHandler(retryPolicy);
Run Code Online (Sandbox Code Playgroud)

如果收到 401,我需要刷新 http 客户端上的不记名令牌。因此,在完美的世界中,以下代码将完全实现我想要完成的任务

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(resp => resp.StatusCode == HttpStatusCode.Unauthorized)
    .WaitAndRetryAsync(3, 
        retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
        onRetry: (resp, timeSpan, context) =>
        {
            var newToken = GetNewToken();
            
            //httpClient doesn't …
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient .net-core polly refresh-token

12
推荐指数
1
解决办法
6621
查看次数

Polly 策略无法使用“AddPolicyHandler”工作

我有一个应用程序请求经过身份验证的服务,需要通过access_token.

我的想法是在过期时使用 Polly 重试access_token

我在 .NET Core 3.1 应用程序中使用 Refit (v5.1.67) 和 Polly (v7.2.1)。

服务注册如下:

services.AddTransient<ExampleDelegatingHandler>();

IAsyncPolicy<HttpResponseMessage> retryPolicy = Policy<HttpResponseMessage>
    .Handle<ApiException>()
    .RetryAsync(1, (response, retryCount) =>
    {
        System.Diagnostics.Debug.WriteLine($"Polly Retry => Count: {retryCount}");
    });

services.AddRefitClient<TwitterApi>()
    .ConfigureHttpClient(c =>
    {
        c.BaseAddress = new Uri("https://api.twitter.com/");
    })
    .AddHttpMessageHandler<ExampleDelegatingHandler>()
    .AddPolicyHandler((sp, req) =>
    {
        //this policy does not works, because the exception is not catched on 
        //"Microsoft.Extensions.Http.PolicyHttpMessageHandler" (DelegatingHandler)
        return retryPolicy;
    });
Run Code Online (Sandbox Code Playgroud)
public interface TwitterApi
{
    [Get("/2/users")]
    Task<string> GetUsers();
}
Run Code Online (Sandbox Code Playgroud)
public class ExampleDelegatingHandler : DelegatingHandler …
Run Code Online (Sandbox Code Playgroud)

c# dotnet-httpclient refit .net-core polly

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

使用字典 System.Text.Json 将 json 反序列化为对象

我正在开发一个 .Net 6.0 项目,我想从 Newtonsoft.Json 迁移到 System.Text.Json。到目前为止,除了以下内容之外,大多数都可以正常工作:

\n

我有这个 json:

\n
[\n   {\n      "Key":"ValidateRequired",\n      "LocalizedValue":{\n         "fr-FR":"Ce champ est obligatoire.",\n         "en-GB":"This field is required.",\n         "nl-BE":"Dit is een verplicht veld.",\n         "de-DE":"Dieses Feld ist ein Pflichtfeld."\n      }\n   },\n   {\n      "Key":"ValidateEmail",\n      "LocalizedValue":{\n         "fr-FR":"Veuillez fournir une adresse \xc3\xa9lectronique valide.",\n         "en-GB":"Please enter a valid email address.",\n         "nl-BE":"Vul hier een geldig e-mailadres in.",\n         "de-DE":"Geben Sie bitte eine g\xc3\xbcltige E-Mail-Adresse ein."\n      }\n   },\n   {\n      "Key":"ValidateUrl",\n      "LocalizedValue":{\n         "fr-FR":"Veuillez fournir une adresse URL valide.",\n         "en-GB":"Please enter a valid URL.",\n         "nl-BE":"Vul …
Run Code Online (Sandbox Code Playgroud)

c# json.net system.text.json asp.net-core-6.0

11
推荐指数
1
解决办法
1万
查看次数

如何使用 ILoggerFactory 记录 Polly 的重试

或者:如何从静态方法记录。

https://github.com/App-vNext/Polly你可以看到像这样的例子,其中记录器神奇地可用:

Policy
  .Timeout(30, onTimeout: (context, timespan, task) => 
    {
        logger.Warn($"{context.PolicyKey} at {context.ExecutionKey}: execution timed out after {timespan.TotalSeconds} seconds.");
    });
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我使用IHttpClientFactorydotnet core 2.1 中的新模式,并将其添加到我的 Startup.csConfigureServices方法中:

    services.AddHttpClient<IMySuperHttpClient, MySuperHttpClient>()
        .AddPolicyHandler(MySuperHttpClient.GetRetryPolicy())
        .AddPolicyHandler(MySuperHttpClient.GetCircuitBreakerPolicy());
Run Code Online (Sandbox Code Playgroud)

静态且GetRetryPolicy看起来像这样:

internal static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
    return HttpPolicyExtensions
        .HandleTransientHttpError()
        .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
        .WaitAndRetryAsync(
            retryCount: 4,
            sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
            onRetry: OnRetry);
}
Run Code Online (Sandbox Code Playgroud)

其中OnRetry方法也必须是静态的:

private static void OnRetry(DelegateResult<HttpResponseMessage> delegateResult, TimeSpan timespan, Context context)
{
    // var logger = ?? …
Run Code Online (Sandbox Code Playgroud)

c# logging dependency-injection polly asp.net-core-2.1

10
推荐指数
1
解决办法
5701
查看次数

如何使用 TypeScript 编写的 API Gateway 在 VS Code 中调试本地 AWS Lambda 函数?

我们即将开始使用 Lambda 函数。
我们有必须使用 TypeScript 的技术限制。
当从 Postman 调用相关端点时,我希望能够在 VS Code 中调试我的 ts 文件。

所以,我们有以下开发环境:

  • 视窗 10
  • Docker for Windows(使用 Hyper-V 而不是 WSL 2)
  • 打字稿 4.1
  • 节点 12.17
  • SAM CLI 1.13.2

我已经使用sam initHello World 模板来生成初始文件夹结构。
我已经对其进行了增强(主要基于本文)以使用 TypeScript。

文件夹结构

.
??? template.yaml
??? .aws-sam
??? .vscode
|   ??? launch.json
??? events
??? hello-world
|   ??? dist
|       ??? app.js
|       ??? app.js.map
|   ??? src  
|       ??? app.ts
|   ??? package.json
|   ??? tsconfig.json
Run Code Online (Sandbox Code Playgroud)

template.yaml

.
??? …
Run Code Online (Sandbox Code Playgroud)

amazon-web-services node.js typescript aws-lambda aws-sam-cli

10
推荐指数
2
解决办法
2233
查看次数

`CancellationTokenSource.TryReset` 的用例是什么?

CancellationTokenSourceTryReset()会员。该文档看起来如此严格,让我想知道它为什么存在。

  • 只有在没有人调用Cancel()它的情况下它才会起作用。
  • 仅当使用其令牌发出的任何先前异步操作已完成时才有效,这意味着(我认为)我需要挂起我的任务对象来跟踪它是否仍在运行
  • 当其他人试图取消操作时调用是不安全的,需要

那么人们为什么要费心呢TryReset?为什么不简单地为每个异步操作创建一个全新的CancellationTokenSource,然后在操作完成且不再需要取消后将其丢弃?CancellationTokenSource创建一个对象是否非常昂贵?

.net c# task-parallel-library cancellationtokensource

9
推荐指数
1
解决办法
1263
查看次数