Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
895 views
in Technique[技术] by (71.8m points)

c# - Refresh Token using Polly with Typed Client

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

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.

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?

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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
            });
        });
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...