Copied to clipboard

Flag this post as spam?

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

  • Michael Duffy 5 posts 95 karma points
    1 week ago
    Michael Duffy

    I'm deploying our site to Umbraco Cloud, and I need the Development and the Live environment to hit different URLs for the RESTful APIs the site requires. Ideally I'd like to add the configs to appsettings.Development.json and appsettings.Production.json, but I'm unsure how to use that config directly in the cshtml files to pass the URLs into the DOM or set them in a javascript file in /scripts.

    Umbraco 11.4.2 for the deploy.

    Thanks for any and all help!

  • Dennis Adolfi 1082 posts 6444 karma points MVP 5x c-trib
    1 week ago
    Dennis Adolfi

    Hi Michael.

    You can use appsettings.Development.json and appsettings.Production.json etc, and in the top of your cshtml view you should be able go use:

    @using Microsoft.Extensions.Configuration
        var apiBaseUrl = Configuration.GetSection("ApiBaseUrl").Value;

    And then to use this variable in JS:

        var apiBaseUrl = @Html.Raw(Json.Serialize(apiBaseUrl)); 

    Hope that will work for you!

  • Michael Duffy 5 posts 95 karma points
    1 week ago
    Michael Duffy

    Thanks for the reply, Dennis, but that approach doesn't seem to work in Umbraco 11. Microsoft.Extensions.Configuration doesn't define a Configuration object, and System.Configuration doesn't have a static version of GetSection().

    All the other docs I've seen talk about passing configuration via DI, but that's not going to work with .cshtml files of course.

    Using Microsoft.Extensions.Configuration I can create an instance like:

    var configuration = new ConfigurationBuilder().Build();
    var myValue = configuration.GetValue<string>("myKey");

    But that builds an empty configuration. In other dotNet Core apps I'd grab the config from the builder object returned from "WebApplication.CreateBuilder(args)" call in Program.cs, but that's only going to work if I'm writing my own controller or something.

    Are there any examples out there on how to get the config with Umbraco 9+?


  • Michael Duffy 5 posts 95 karma points
    1 week ago
    Michael Duffy

    After spending the entire day reading through all the Umbraco documentation I could find and finding absolutely nothing on the topic, I finally jumped over to reading through Razor docs and found the answer.

    At the top of the view, we need to add:

    @using Microsoft.Extensions.Configuration
    @inject IConfiguration Configuration

    Then in the body of the View in the C# sections we can look up values in appsettings like:

    var myValueOne= @Configuration["myTopLevelKey"];
    var myValueTwo = @Configuration["mySection:myKey"];

    Jeeze this wasted a bunch of time figuring this out... :-(

Please Sign in or register to post replies

Write your reply to: