System.NullReferenceException 从 appSettings.json 访问基地 URL

System.NullReferenceException on accessing the Base URL from the appSettings.json

我在 appsettings.json 中有基础 URL,如下所示

  "RM": {
    "BaseAddress": "https://rm-dev.abc.org/"
  },

在 Class 中,我正在尝试调用此端点

public class InventorySearchLogic
    {
        private readonly SMContext _context;
        private readonly IConfiguration _iconfiguration;
        public InventorySearchLogic(SMContext context, IConfiguration iconfiguration)
        {
            _context = context;
            _iconfiguration = iconfiguration;
        }

        public InventorySearchLogic(SMContext context)
        {
        } 

  public async Task<string> GetRoomID(string roomName)
        {
            //string rmID = "";
            using (var client = new HttpClient())
            {
                RmRoom retRoom = new RmRoom();
                client.BaseAddress = new Uri(_iconfiguration.GetSection("RM").GetSection("BaseAddress").Value);
                client.DefaultRequestHeaders.Accept.Clear();

调试时会抛出类似 System.NullReferenceException: Message=Object reference not set to an instance of an object. how to access the base URL from appsettings.json

这样的错误

我不确定如何使用 ConfigurationBuilder(),因为我有不同的 apSettings.json 文件,每个环境都有一个文件,例如 appsettings.Development.jsonappsettings.QA.jsonappsettings.PROD.json

下面是我的创业公司

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

            services.AddControllersWithViews();
            services.AddSession();
            services.AddMemoryCache();
            services.AddDbContextPool<SurplusMouseContext>(options =>
                {
                    options.UseSqlServer(Configuration.GetConnectionString("SMConnectionStrings"),
                  sqlServerOptionsAction: sqlOptions =>
                  {
                      sqlOptions.EnableRetryOnFailure();
                  });
                });
            services.AddHttpContextAccessor();
            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddRazorPages()
                 .AddMicrosoftIdentityUI();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseSession();
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Customers}/{action=Index}/{id?}");
            });
        }
    }

Program.cs

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

您已经在您的服务中注入 IConfiguration 并将其保存为 _iconfiguration假设这不是空值,那么只需使用 .GetValue 来检索一个值。

string baseAddress = _iconfiguration.GetSection("RM").GetValue<string>("BaseAddress");

阅读更多关于 ASP.Net configuration


嗯,好像_iconfiguration也是空的。

您在评论中指出您正在从控制器创建InventorySearchLogic的实例,例如

// inside controller logic
var searchLogic = new InventorySearchLogic(_context, _iconfiguration);

这是错误的做法。相反,您应该将此 class 注册为 DI 服务(尽管您还应该添加一个接口,但现在没有必要)。

在您的 Startup 的 ConfigureServices 方法中,添加

services.AddTransient<InventorySearchLogic>();

然后不是手动创建类型 InventorySearchLogic 的变量,而是通过 DI

请求它
// your controller constructor
private readonly InventorySearchLogic searchLogic;
public MyController(InventorySearchLogic searchLogic)
{
    this.searchLogic = searchLogic;
}

这样,InventorySearchLogic 的构造函数就可以正确获取它正在寻找的 DI 服务。您将不得不移动 SMContext context。也许将其移至方法的参数?