简体   繁体   中英

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();
        }
    }

}

在此处输入图像描述

How to fix?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM