Intercept C# HttpClient GetAsync

北慕城南 提交于 2019-12-09 18:43:31

问题


I have a web project (C#, MVC5 but no WebAPI) and a simple HTTP REST client that is calling an external REST service and acquires an accessToken etcing.

I want to check the response from all my Get/PostAsync calls for statusCode 401 but I see that I can only override the SendAsync method when implementing the DelegatingHandler.

class CustomDelegatingHandler : DelegatingHandler
{
    async protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {

Is there something else I can do so as not to change the implementation of all my async calls to use SendAsync?

(What I really really want to do is refresh the accessToken.)


回答1:


I think you're on the right track. You wouldn't need to change your calls to use SendAsync instead of GetAsync, PostAsync, etc though. Rather, you'd need to change how you instantiate HttpClient:

var client = new HttpClient(new CustomDelegatingHandlerTokenRefresher());
// GetAsync, PostAsync, etc will hit your handler



回答2:


Use the Decorator or Interceptor pattern.

Example concrete decorator:

public class CustomDelegatingHandlerTokenRefresher() : DelegatingHandler
{
    public CustomDelegatingHandlerTokenRefresher(DelegatingHandler handler)
    {
        InnerHandler = handler;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
      HttpRequestMessage request, CancellationToken cancellationToken)
    {
        RefreshToken();
        return await InnerHandler.SendAsync(request, cancellationToken);
    }
}


来源:https://stackoverflow.com/questions/29106664/intercept-c-sharp-httpclient-getasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!