Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Bor 12 posts 125 karma points
    Oct 12, 2021 @ 13:26
    Bor
    1

    How to add SurfaceController URL to Umbraco Server Variables to access from custom Umbraco DataType

    I'm porting code for custom DataType from U8 to U9.
    This DataType is calling a Surface controller to retrieve some data.

    In the Umbraco v version I access the URL from the "Umbraco.Sys.ServerVariables" like:

    var apiUrl = Umbraco.Sys.ServerVariables['MainKey']['Controller1URL'];

    We set the value to this variable on project startup on the event ServerVariablesParser.Parsing like:

        // https://our.umbraco.com/documentation/extending/version7-assets
        public class BackofficeControllersURLListRegistrator : IComponent
        {
            public void Initialize()
            {
                Umbraco.Web.JavaScript.ServerVariablesParser.Parsing += ServerVariablesParser_Parsing;
            }
    
            private void ServerVariablesParser_Parsing(object sender, Dictionary<string, object> e)
            {
                if (HttpContext.Current == null) throw new InvalidOperationException("HttpContext is null.");
    
                var backofficseUrls = new Dictionary<string, string>();
    
                var url = new System.Web.Mvc.UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));
                backofficseUrls.Add(
                    "Controller1URL", url.GetUmbracoApiService<Controllers.ApiControllers.Test1Controller>(controller => controller.TestFunction())
                );
    
                e.Add("MainKey", backofficseUrls);
            }
    
            public void Terminate()
            {
            }
        }
    

    How would we in Umbraco 9 hook up to ServerVariablesParser Notification if it exists and how to retrieve Controller function URL, so I can retreave it in DataType JS code like in previus versions?

    Any help would be extremally appreciated.

  • Andy Butland 422 posts 2334 karma points MVP 4x hq c-trib
    Oct 12, 2021 @ 15:58
    Andy Butland
    102

    To do this in V9 you'll need to look at creating a notification handler.

    Specifically a class like this that applies the changes you need:

    public class ServerVariablesParsingHandler :
        INotificationHandler<ServerVariablesParsingNotification>
    {
        public void Handle(ServerVariablesParsingNotification notification)
        {
            // Your logic here.
        }
    }
    

    You then need this line in a composer or startup extension method to register the handler:

    builder.AddNotificationHandler<ServerVariablesParsingNotification, ServerVariablesParsingHandler>();
    

    Hope that helps.

    Andy

Please Sign in or register to post replies

Write your reply to:

Draft