Quantcast
Channel: damienbod – Software Engineering
Viewing all articles
Browse latest Browse all 353

Injecting Configurations in Razor Views in ASP.NET Core

$
0
0

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

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": "http://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 IConfigurationRoot in the constructor.

public Startup(IHostingEnvironment env)
{
	var builder = new ConfigurationBuilder()
		.SetBasePath(env.ContentRootPath)
		.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
		.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
		.AddEnvironmentVariables();
	Configuration = builder.Build();
}

public IConfigurationRoot 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.AddMvc();
}

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



Viewing all articles
Browse latest Browse all 353

Trending Articles