Home > Mobile >  System.NullReferenceException on accessing the Base URL from the appSettings.json
System.NullReferenceException on accessing the Base URL from the appSettings.json

Time:05-11

I have the Base URL within the appsettings.json like below

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

With in the Class where I am trying to make a call this endpoint

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

When debugging it throws error like System.NullReferenceException: Message=Object reference not set to an instance of an object. how to access the base URL from appsettings.json

I am not sure how to use the ConfigurationBuilder() as I have different apSettings.json file one for each environment like appsettings.Development.json , appsettings.QA.json, appsettings.PROD.json

enter image description here

Below is my Startup

    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?}");
            });
        }
    }

CodePudding user response:

You're already injecting an IConfiguration in your service and saving it as _iconfiguration. Assuming that's not the null value, then simply use .GetValue to retrieve a value.

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

Read more about ASP.Net configuration

CodePudding user response:

If your setting is in application settings, you can access it with the following: Properties.Settings.Default.{yourVariableName}

  • Related