Skip to content

Extending Core

Dennis Heutinck edited this page Oct 9, 2022 · 1 revision

Create, search and update redirects in code

Use the public api to create, search and update redirects in code:

using UrlTracker.Core;
using UrlTracker.Core.Models;

public class MyService
{
    private readonly IUmbracoContextFactory _umbracoContextFactory;
    private readonly IRedirectService _redirectService;

    public MyService(IUmbracoContextFactory umbracoContextFactory, IRedirectService redirectService)
    {
        _umbracoContextFactory = umbracoContextFactory;
        _redirectService = redirectService
    }

    public async Task MyMethod()
    {
        using var cref = _umbracoContextFactory.EnsureUmbracoContext();

        // Create a new redirect
        Redirect redirect = new Redirect
        {
            SourceUrl = "/home/lorem/ipsum"
            TargetRootNode = cref.UmbracoContext.Content.GetById(1234),
            TargetNode = cref.UmbracoContext.Content.GetById(1235),
            TargetStatusCode = HttpStatusCode.Found,
            Culture = "en-US"
        }

        // Add the redirect and reassign the variable. The new value has an id assigned.
        //    If the redirect is invalid, this method will throw an ArgumentException.
        //    Check the inner exception for details.
        redirect = await _redirectService.AddAsync(redirect);

        // Change the redirect
        redirect.TargetNode = null;
        redirect.TargetUrl = "https://example.com/";

        // Update the redirect and reassign the variable
        //    If the redirect is invalid, this method will throw an ArgumentException.
        //    Check the inner exception for details.
        redirect = await _redirectService.UpdateAsync(redirect);

        // Search for redirects
        RedirectCollection searchResults = await _redirectService.GetAsync(skip: 0, take: 10, query: "homepage");
    }
}
Clone this wiki locally