Search code examples
c#.nethttpdotnet-httpclientpolly

Does the order in which you add handlers matter when registering an HTTP client? - C# .NET


When you are registering an HTTP client in .NET as such

return services
            .Configure<Options>(configuration.GetSection(nameof(Options)))
            .AddHttpClient<IService, Service>()
                .AddPolicyHandlerFromRegistry("Field")
                .AddOAuthHttpMessageHandler(() => configuration.GetBinded<Options>().RealmScope)
                .AddHttpMessageHandler<TrackingHandler>()
                .Services;

Does the order in which you add handlers matter? Would it cause an issue to have AddPolicyHandlerFromRegistry before AddOAuthHttpMessageHandler?


Solution

  • *Does the order which you add handlers matter?

    • YES

    See this for Policy handler

    https://stackoverflow.com/a/63700841/850980

    or this for DI services

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0#jcp

    Would it cause an issue to have "AddPolicyHandlerFromRegistry" before "AddOAuthHttpMessageHandler"?

    I think it depends on further implementation details.