以下两种设置 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
我是 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)
预先感谢您的支持。
问候,
我在启动时有
(更新:解决方案是将 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) 我有一个看起来像这样的政策
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) 我有一个应用程序请求经过身份验证的服务,需要通过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) 我正在开发一个 .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) 或者:如何从静态方法记录。
从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)
在我的代码中,我使用IHttpClientFactory
dotnet 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) 我们即将开始使用 Lambda 函数。
我们有必须使用 TypeScript 的技术限制。
当从 Postman 调用相关端点时,我希望能够在 VS Code 中调试我的 ts 文件。
所以,我们有以下开发环境:
我已经使用sam init
Hello 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
CancellationTokenSource
有TryReset()
会员。该文档看起来如此严格,让我想知道它为什么存在。
Cancel()
它的情况下它才会起作用。那么人们为什么要费心呢TryReset
?为什么不简单地为每个异步操作创建一个全新的CancellationTokenSource
,然后在操作完成且不再需要取消后将其丢弃?CancellationTokenSource
创建一个对象是否非常昂贵?
c# ×9
.net-core ×3
asp.net-core ×3
polly ×3
.net ×1
asp.net5 ×1
async-await ×1
aws-lambda ×1
aws-sam-cli ×1
http-get ×1
json.net ×1
logging ×1
node.js ×1
refit ×1
routes ×1
typescript ×1