You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Umbraco9如何将SurfaceController URL添加到服务器变量供自定义DataType调用

实现自定义ServerVariables通知处理器

Umbraco9已经将原来的ServerVariablesParser.Parsing事件调整为ServerVariablesParsingNotification通知,你需要实现INotificationHandler<ServerVariablesParsingNotification>接口完成变量注入,无需再使用旧版的IComponent:

using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Http;
using Umbraco.Extensions;

public class BackofficeControllersURLListRegistrator : INotificationHandler<ServerVariablesParsingNotification>
{
    private readonly LinkGenerator _linkGenerator;
    private readonly IHttpContextAccessor _httpContextAccessor;

    // 依赖注入获取所需服务
    public BackofficeControllersURLListRegistrator(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor)
    {
        _linkGenerator = linkGenerator;
        _httpContextAccessor = httpContextAccessor;
    }

    public void Handle(ServerVariablesParsingNotification notification)
    {
        if (_httpContextAccessor.HttpContext == null)
        {
            throw new InvalidOperationException("HttpContext is null.");
        }

        var backofficeUrls = new Dictionary<string, string>();
        // 获取Umbraco Api控制器对应方法的访问地址
        backofficeUrls.Add(
            "Controller1URL", 
            _linkGenerator.GetUmbracoApiService<Controllers.ApiControllers.Test1Controller>(
                controller => controller.TestFunction(), 
                _httpContextAccessor.HttpContext.Request.Scheme,
                _httpContextAccessor.HttpContext.Request.Host)
        );

        // 注入到ServerVariables,键名和旧版保持一致
        notification.ServerVariables.Add("MainKey", backofficeUrls);
    }
}
注册服务到Umbraco DI容器

你需要通过Composer注册通知处理器和依赖的服务:

using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

public class ServerVariablesComposer : IComposer
{
    public void Compose(IUmbracoBuilder builder)
    {
        // 注册HttpContext访问器(如果项目未提前注册需要加这一行)
        builder.Services.AddHttpContextAccessor();
        // 注册我们实现的通知处理器
        builder.AddNotificationHandler<ServerVariablesParsingNotification, BackofficeControllersURLListRegistrator>();
    }
}
前端调用方式

JS侧访问逻辑和旧版完全一致,不需要做修改:

var apiUrl = Umbraco.Sys.ServerVariables['MainKey']['Controller1URL'];
注意事项
  • 如果你要获取的是Surface控制器的地址,替换GetUmbracoApiService为GetPathByAction方法,指定对应控制器名、动作名、区域参数即可
  • 控制器继承规则和旧版一致,Api控制器需要继承UmbracoApiController,Surface控制器需要继承SurfaceController
  • 确保引用了Umbraco.Extensions命名空间,否则找不到GetUmbracoApiService扩展方法

内容的提问来源于stack exchange,提问作者BRap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:45:00