简体   繁体   English

ASP.NET Core WebAPI 6 无法从配置中获取值,如何解决?

[英]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.我正在尝试将 ASP.NET Core 3.x 的源代码迁移到版本 6.x。 Source code https://www.c-sharpcorner.com/article/custome-jwt-token-and-asp-net-core-web-api//download/JWTTokenPOC.zip .源代码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当前项目,我正在使用 ASP.NET Core WebAPI 6. 我的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文件applications.Development.json .开发.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我的Program.cs有错误

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.您不能使用构造函数在Program.cs中注入服务。 This is where the application starts, dependency injection container is not created yet.这是应用程序启动的地方,依赖注入容器尚未创建。 Instead you can access configuration using builder.Configuration :相反,您可以使用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 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0#access-configuration-in-programcs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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