Vy Do
Vy Do

Reputation: 52508

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

{
  "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?

Upvotes: 1

Views: 1240

Answers (1)

Dimitris Maragkos
Dimitris Maragkos

Reputation: 11312

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://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0#access-configuration-in-programcs

Upvotes: 2

Related Questions