Skip to content

Use named HttpClients#15375

Merged
Zeegaan merged 14 commits intorelease/13.0from
v13/feature/use-http-factory-to-create-httpclient
Dec 7, 2023
Merged

Use named HttpClients#15375
Zeegaan merged 14 commits intorelease/13.0from
v13/feature/use-http-factory-to-create-httpclient

Conversation

@Zeegaan
Copy link
Member

@Zeegaan Zeegaan commented Dec 6, 2023

Notes

  • Adds a named IHttpClient client for Webhook firing.
  • Uses the IHttpClientFactory to then create a HttpClient, instead of just newing it up.
  • This means that users of umbraco can now overwrite the named HttpClient with their configuration.

How to test

  • Create a Document type with allow as root set to true.

  • Create a webhook (getting url from webhook.site or other testing environment)

  • Set the Content is published event.

  • Create some content.

  • Assert your endpoint gets called.

  • We can assert that you can overwrite configuration, with the test composer down below:

You can then overwrite our named client like:

using System.Diagnostics;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Composing;

namespace Umbraco.Cms.Web.UI;

public class MyComposer : IComposer
{
    public void Compose(IUmbracoBuilder builder)
    {
        builder.AddComponent<HttpClientComponent>();

        builder.Services.AddHttpClient(Constants.HttpClients.WebhookFiring, client =>
        {
            client.DefaultRequestHeaders.UserAgent.ParseAdd("Umbraco");
        });

        builder.Services.AddHttpClient(Constants.HttpClients.WebhookFiring, client =>
        {
            client.DefaultRequestHeaders.Referrer = new Uri("http://example.com/");
        });
    }

    private class HttpClientComponent(IHttpClientFactory httpClientFactory) : IComponent
    {
        public void Initialize()
        {
            var client = httpClientFactory.CreateClient(Constants.HttpClients.WebhookFiring);

            Debug.Assert(client.DefaultRequestHeaders.UserAgent.Count > 0, "User agent must be set!");
            Debug.Assert(client.DefaultRequestHeaders.Referrer != null, "Referrer should be set!");
            Debugger.Break();
        }

        public void Terminate()
        { }
    }
}

…create-httpclient' into v13/feature/use-http-factory-to-create-httpclient

# Conflicts:
#	src/Umbraco.Infrastructure/BackgroundJobs/Jobs/WebhookFiring.cs
@Zeegaan Zeegaan merged commit 4ff2572 into release/13.0 Dec 7, 2023
@Zeegaan Zeegaan deleted the v13/feature/use-http-factory-to-create-httpclient branch December 7, 2023 08:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants