受欢迎的博客标签

How to read, unable to read appsettings.json values ASP.NET Core 6.x controllers

Published

Let’s start with the code.  I want to read from my appsettings.json file from within one of my ASP.NET Core controllers, for example.

.Net 6.x   updated 2021-10-27

Configuration in ASP.NET Core 6.x

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Add custom services to the container.
builder.Services.AddSingleton<IUserServices, BlogUserServices>();
builder.Services.AddSingleton<IBlogService, FileBlogService>();

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddMetaWeblog<MetaWeblogService>();

//Add  Configure Options
//https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/configuration/index/samples/6.x/ConfigSample/Program.cs
builder.Configuration.AddJsonFile("appsettings.json");

builder.Services.Configure<BlogSettings>(
    builder.Configuration.GetSection("blog"));

var app = builder.Build();

 

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

How to use

using Microsoft.Extensions.Options;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using System.Xml;

using Miniblog.Core.Models;
using Miniblog.Core.Services;


namespace Miniblog.Core.Controllers
{
    public class BlogController : Controller
    {

        private readonly IBlogService blog;

     

        private readonly IOptionsSnapshot<BlogSettings> settings;

        public BlogController(IBlogService blog, IOptionsSnapshot<BlogSettings> settings)
        {
            this.blog = blog;
            this.settings = settings;
           
        }
...
 public async Task<IActionResult> Category(string category, int page = 0)
        {
            // get posts for the selected category.
            var posts = this.blog.GetPostsByCategory(category);

            // apply paging filter.
            var filteredPosts = posts.Skip(this.settings.Value.PostsPerPage * page).Take(this.settings.Value.PostsPerPage);  //here

...

.Net 5.x

First, add a setting to the applicationsettings.json file, similar to the following with a name of API_URL, for example and give it a value.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "API_URL": "thebestappsettingintheworld.ever"
}

Next, add this line of code to the Startup(IConfiguration configuration) method within the Startup.cs file.

   public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment _webHostEnvironment)
        {
            Configuration = configuration;
            //create configuration
            //Configuration = new ConfigurationBuilder()
            //    .SetBasePath(webHostEnvironment.ContentRootPath)
            //    .AddJsonFile("App_Data/appsettings.json", optional: false, reloadOnChange: true)
            //    .AddEnvironmentVariables()
            //    .Build();

            Configuration = new ConfigurationBuilder()
                .SetBasePath(_webHostEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();
        }

        public IConfiguration Configuration { get; }
...
}

 

Finally, in the controller of choice, add the following code.

using Microsoft.Extensions.Configuration;  

namespace mostawesomenamespaceever.Controllers

{   

 public class HomeController : Controller   

 {      

 readonly IConfiguration _configuration;          

  public HomeController(IConfiguration configuration)      

 {        

  _configuration = configuration;   

  }        

 public IActionResult About()     

  {  

       var URL = _configuration["API_URL"];        

 ViewData["Message"] = $"Your application description page. The URL value is {URL}";      

   return View();     

  }  

  }

}