Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASP.NET Core WebAPI 6 cannot get value from configuration, how to fix?

I am trying migration source code of a ASP.NET Core 3.x to version 6.x . Source code https://www.c-sharpcorner.com/article/custome-jwt-token-and-asp-net-core-web-api//download/JWTTokenPOC.zip .

Current project, I am using ASP.NET Core WebAPI 6 . My appsettings.json

{
  /*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform
*/
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "qualified.domain.name",
    "TenantId": "22222222-2222-2222-2222-222222222222",
    "ClientId": "11111111-1111-1111-11111111111111111",

    "Scopes": "access_as_user",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "ConnectionStrings": {
      "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=acc200;User Id=postgres;Password=postgres;"
    }
  },
  "AllowedHosts": "*",
  "AppSettings": {
    "Key": "986ghgrgtru989ASdsaerew13434545439",
    "Issuer": "atul1234"
  }
}

File applications.Development.json

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "AllowedHosts": "*",

    "AppSettings": {
      "Key": "986ghgrgtru989ASdsaerew13434545435",
      "Issuer": "atul1234"
    },
    "ConnectionStrings": {
      "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=foo;User Id=postgres;Password=postgres;"
    }
  }
}

My Program.cs has error

using acc7.Data;
using JWTTokenPOC.Helper;
using JWTTokenPOC.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;
using System.Configuration;
using AuthenticationService = JWTTokenPOC.Service.AuthenticationService;

namespace acc7
{
    public class Program
    {

        public IConfiguration Configuration { get; }


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

        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            // Add services to the container.
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
            var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
            // builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString));
            builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql("Server=127.0.0.1;Port=5432;Database=acc200;User Id=postgres;Password=postgres;"));
            builder.Services.AddControllers();

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

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            builder.Services.AddCors();
            builder.Services.AddScoped<IUserService, UserService>();
            builder.Services.AddScoped<JWTTokenPOC.Service.IAuthenticationService, AuthenticationService>();

            var app = builder.Build();
            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseAuthorization();


            // set global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseMiddleware<JwtMiddleware>();

            app.MapControllers();
            app.Run();
        }
    }

}

enter image description here

How to fix?

>Solution :

You can’t inject services in Program.cs using constructor. This is where the application starts, dependency injection container is not created yet. Instead you can access configuration using builder.Configuration:

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading