使用Polly和Typed Client刷新令牌

编程入门 行业动态 更新时间:2024-10-25 12:27:24
本文介绍了使用Polly和Typed Client刷新令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个在服务中配置的Typed Client,并且我正在使用Polly进行临时故障的重试.

I have a Typed Client which i have configured in the services and i am using Polly to make retries for transient faults.

目标:我想利用Polly实现刷新令牌,只要目标站点收到401响应,我都希望Polly刷新令牌并再次继续初始请求.

Aim: I want to make use of Polly to implement refresh token, whenever there is a 401 response from the target site, i want Polly to refresh the token and continue the initial request again.

问题是类型客户端具有所有api方法和刷新令牌方法,当从类型客户端发起请求时,如何再次访问类型客户端以调用刷新令牌并继续初始请求?

The problem is the typed client has all the api methods and the refresh token method, when the request is initiated from the typed client how do i access the typed client again to call the refresh token and continue the initial request?

onRetry中的上下文"为将任何对象添加到字典中提供了一些支持,但是我无法访问SetPolicyExecutionContext('someContext')方法,并且我不想在发起调用之前将其添加到所有方法中因为有很多API.

The 'Context' in onRetry provides some support to add any object to the dictionary, but i am unable to access the SetPolicyExecutionContext('someContext') method and i do not want to add this on all the methods before initiating the call as there's whole lot of API.

// In Service Configuration // Refresh token policy var refreshTokenPolicy = Polly.Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized) .RetryAsync(1, (response, retrycount, context)) => { if(response.Result.StatusCode == HttpStatusCode.Unauthorized) { // Perform refresh token } } // Typed Client services.AddHttpClient<TypedClient>(); public class TypedClient { private static HttpClient _client; public TypedClient(HttpClient client) { _client = client; } public string ActualCall() { // some action } public string RefreshToken() { // Refresh the token and return } }

推荐答案

您可以使用AddPolicyHandler,它的重载可以通过IServiceProvider.因此,您所需要做的就是:

You can useAddPolicyHandler which has an overload that passesIServiceProvider. So all you need to do is something like:

services.AddHttpClient<TypedClient>() .AddPolicyHandler((provider, request) => { return Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized) .RetryAsync(1, (response, retryCount, context) => { var client = provider.GetRequiredService<TypedClient>(); // refresh auth token. }); }); });

更多推荐

使用Polly和Typed Client刷新令牌

本文发布于:2023-10-29 09:45:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539371.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   Polly   Typed   Client

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!