Quantcast
Channel: TechNet Blogs
Viewing all articles
Browse latest Browse all 34890

Tip of the Week: How to access configuration from Controller in ASP.NET Core 2.0?

$
0
0

You defined your config structure in appsetings.json file, and you what to access this data in a Controller in your ASP.NET MVC or WebAPI project based on .NET Core 2.0. There are a couple of options, but one of the easiest is that.

The example structure of your configuration in appsetings.json file is below.

appsetings.json

[js]{
"MySection": {
"MyFirstConfig": "Secret string",
"MySecondConfig": {
"MyFirstSubConfig": true,
"MySecondSubConfig": 32
}
}
}[/js]

Using built-in support for Dependency Injection, you can inject configuration data to Controller. Use AddSingleton method to add a singleton service in Startup.cs file. Just add services.AddSingleton(Configuration); in ConfigureServices.

Startup.cs

[csharp]public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IConfiguration>(Configuration);
}[/csharp]

In your Controller declare IConfiguration variable, and assign configuration in a constructor. To retrieve configuration data at Controller use:

  • _configuration["MySection:MySecondConfig:MyFirstSubConfig"] (each configuration key separated by ":") or
  • _configuration.GetSection("MySection")["MySecondConfig:MySecondSubConfig"] (GetSection method with you section name as variable, and next configuration keys separated by ":" as Index).

Do not forget about using Microsoft.Extensions.Configuration; at the beginning 😉

HomeController.cs

[csharp]using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
private IConfiguration _configuration;

public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}

public IActionResult Index()
{
ViewData["MySectionMyFirstConfig"] = _configuration["MySection:MyFirstConfig"];
ViewData["MySectionMySecondConfigMyFirstSubConfig"] = _configuration["MySection:MySecondConfig:MyFirstSubConfig"];
ViewData["MySectionMySecondConfigMySecondSubConfig"] = _configuration.GetSection("MySection")["MySecondConfig:MySecondSubConfig"];
return View();
}
}
}[/csharp]

Example output:

Index.cshtml

[html]<p>
MySectionMyFirstConfig <strong>@ViewData["MySectionMyFirstConfig"]</strong><br />
MySectionMySecondConfigMyFirstSubConfig <strong>@ViewData["MySectionMySecondConfigMyFirstSubConfig"]</strong><br />
MySectionMySecondConfigMySecondSubConfig <strong>@ViewData["MySectionMySecondConfigMySecondSubConfig"]</strong>
</p>[/html]


Viewing all articles
Browse latest Browse all 34890

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>