Injecting Configurations in Razor Views in ASP.NET Core

This article shows how application configurations can be injected and used directly in razor views in an ASP.NET Core MVC application. This is useful when an SPA requires application URLs which are different with each deployment and need to be deployed as configurations in a json or xml file.

Code: https://github.com/damienbod/AspNetCoreInjectConfigurationRazor

2019-07-29 Updated to ASP.NET Core 3.0
2019-01-30 Updated to ASP.NET Core 2.2
2017-08-21 Updated to ASP.NET Core 2.0
2017-02-03 Updated to VS2017 RC3 msbuild3
2017-01-07 Updated to VS2017 csproj

The required configuration properties are added to the ApplicationConfigurations configuration section in the appsettings.json file.

{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "ApplicationConfigurations": {
        "ApplicationHostUrl": "https://damienbod.com/",
        "RestServiceTwo": "https://someapp/api/"
    }
}

An ApplicationConfigurations class is created which will be used to read the configuration properties.

namespace AspNetCoreInjectConfigurationRazor.Configuration
{
    public class ApplicationConfigurations
    {
        public string ApplicationHostUrl { get; set; }

        public string RestServiceTwo { get; set; }
    }
}

In the Startup class, the appsetting.json file is loaded into the IConfiguration in the constructor.

public Startup(IConfiguration configuration)
{
	Configuration = configuration;
}

public IConfiguration Configuration { get; }

The ApplicationConfigurations section is then added to the default ASP.NET Core IoC in the ConfigureServices method in the startup class.

public void ConfigureServices(IServiceCollection services)
{
	services.Configure<ApplicationConfigurations>
	  (Configuration.GetSection("ApplicationConfigurations"));


	services.AddControllersWithViews()
		.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
	services.AddRazorPages();
}

The IOptions object is directly injected into the cshtml razor view using the @inject. The values can then be used and for example, added to input hidden HTML objects, which can then be used from any javascript framework.

@using Microsoft.Extensions.Options;
@using AspNetCoreInjectConfigurationRazor.Configuration;

@inject IOptions<ApplicationConfigurations> OptionsApplicationConfiguration

@{
    ViewData["Title"] = "Home Page";
}

<h2>Injected properties direct from configuration file:</h2>
<ol>
    <li>@OptionsApplicationConfiguration.Value.ApplicationHostUrl</li>
    <li>@OptionsApplicationConfiguration.Value.RestServiceTwo</li>
</ol>

@*Could be used in an SPA app using hidden inputs*@
<input id="ApplicationHostUrl" 
       name="ApplicationHostUrl" 
       type="hidden" 
       value="@OptionsApplicationConfiguration.Value.ApplicationHostUrl"/>
<input id="RestServiceTwo" 
       name="id="RestServiceTwo" 
       type="hidden" 
       value="@OptionsApplicationConfiguration.Value.RestServiceTwo" />

When to application is started, the view is then returned with the configuration properties from the json file and the hidden inputs can be viewed using the F12 debug function in the browser.

AspNetCoreInjectConfigurationRazor_01

Links:

https://docs.asp.net/en/latest/mvc/views/dependency-injection.html

9 comments

  1. […] Injecting Configurations in Razor Views in ASP.NET Core […]

  2. Thank you very much! Helped me a lot!

  3. Bernhard · · Reply

    Thank you. I saved a lot of time.

  4. Hi Damien. It’s been a while! As usual, when I’m looking for something out of the ordinary, it seems you come up in my search for it! Thank you! This is cool. Best regards, Michael

  5. I have a question about where this is located. In ConfigureServices, all other dependencies are scoped. So, what is the scope of services.Configure? Thank you!

  6. Thanks! Solved my issue!

  7. Phillip Holmes · · Reply

    Or.. you could just do this without the fuss.

    @using Microsoft.Extensions.Configuration
    @inject IConfiguration Configuration

    then..

    @Html.Raw(Configuration.GetValue(“ApplicationConfigurations:ApplicationHostUrl”))

  8. Phillip Holmes · · Reply

    okay. your form stripped out code on the getvalue()..

    Or.. you could just do this without the fuss.

    @using Microsoft.Extensions.Configuration
    @inject IConfiguration Configuration

    then..

    @Html.Raw(Configuration.GetValue(“ApplicationConfigurations:ApplicationHostUrl”))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: