1

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

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

enter image description here

user4912134
  • 1,003
  • 5
  • 18
  • 47

1 Answers1

3

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


Well, it seems that _iconfiguration is also null.

You've indicated in the comments that you're creating an instance of InventorySearchLogic from a controller, such as

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

This is the wrong approach. Instead, you should register this class as a DI service (although you should also add an interface, it's not necessary right now).

In your Startup's ConfigureServices method, add

services.AddTransient<InventorySearchLogic>();

Then instead of manually creating a variable of type InventorySearchLogic, request it though DI

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

This way, InventorySearchLogic's constructor correctly gets the DI services it's looking for. You will have to move the SMContext context. Maybe move that to the method's parameters?

gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • I tried as you suggested still it throws the same error because the _iconfiguration is null. I added the screenshot of the error, what could I be missing here – user4912134 May 11 '22 at 14:02
  • Are you doing anything in Program/Setup to add the configuration to DI? https://stackoverflow.com/questions/55790277/dependency-injection-not-working-for-iconfiguration-c-net-core Depending on your target framework, that should be done for you by default. – gunr2171 May 11 '22 at 14:09
  • I have added the `Startup` code here – user4912134 May 11 '22 at 14:11
  • Which framework are you targetting? – gunr2171 May 11 '22 at 14:16
  • .NET 5.0 is the Target Frameworkusing enity framework – user4912134 May 11 '22 at 14:18
  • .Net 5 adds IConfiguration to the DI graph for you. I just tested it with an empty .Net 5 MVC website. Are you sure the `IConfiguration` in your service is `Microsoft.Extensions.Configuration.IConfiguration`? It doesn't make sense that `_iconfiguration` would be null. – gunr2171 May 11 '22 at 14:26
  • I am new to this where should I check, I am passing this `public IConfiguration _iconfiguration { get; } ` from the Controller where I calling this Class `var searchLogic = new InventorySearchLogic(_context, _iconfiguration);` – user4912134 May 11 '22 at 14:31
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244669/discussion-between-gunr2171-and-user4912134). – gunr2171 May 11 '22 at 14:36