Search code examples
orchardcmsorchardcms-1.7orchardcore

Updating an Orchard Core tenant's hostname programmatically


In the Orchard admin dashboard (Multi-Tenancy > Tenants > click Edit for desired tenant), there's a Hostname field. I want to update this field (adding an additional domain) with C# code.

I can change it with IShellSettingsManager, and I see my change when I retrieve the value with IShellSettingsManager. But the change is not shown in the Orchard admin dashboard. When I make the change directly in the dashboard it works, but I need to do it with code.

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using OrchardCore.Environment.Shell;
using OrchardDataApi.Services.Interface;

namespace OrchardDataApi.Services
{
    public class TenantService : ITenantService
    {
        private readonly Lazy<IShellSettingsManager> _lazyShellSettingsManager;

        private IShellSettingsManager ShellSettingsManager => _lazyShellSettingsManager.Value;

        public TenantService(IHttpContextAccessor httpContextAccessor)
        {
            _lazyShellSettingsManager = httpContextAccessor.BuildLazyService<IShellSettingsManager>();
        }

        public async Task<ShellSettings> GetShellSettingsAsync(int websiteId)
        {
            var shellSettings = await ShellSettingsManager.LoadSettingsAsync();
            return shellSettings.SingleOrDefault(x => x.Name == websiteId.ToString());
        }

        public async Task<ShellSettings> UpdateShellSettingsAsync(int websiteId, ShellSettings model)
        {
            await ShellSettingsManager.SaveSettingsAsync(model);
            return await GetShellSettingsAsync(websiteId);
        }

        public async Task<ShellSettings> AddToRequestUrlHostAsync(int websiteId, string domain)
        {
            var model = await GetShellSettingsAsync(websiteId);

            if (model != null)
            {
                var hosts = model.RequestUrlHosts.ToList();
                if (!hosts.Contains(domain))
                {
                    hosts.Add(domain);
                    model.RequestUrlHost = string.Join(',', hosts);
                    model = await UpdateShellSettingsAsync(websiteId, model);
                }
            }

            return model;
        }
    }
}

Solution

  • You need an IShellHost, and after calling SaveSettingsAsync, you need to do this:

    await ShellHost.ReloadShellContextAsync(model);