0

I am trying to get my connection string from my appsettings.json file and use it in my startup file, but I keep getting am error

Value cannot be null. Parameter name: connectionString.

This is my Appsetting.json file:

{
  "Project": {
    "ConnectionStrings": "Data Source=(local)\\SQLSERVER; Database=RecommendationSite; Persist Security Info=false; User ID='sa'; Password='sa'; MultipleActiveResultSets=True; Trusted_Connection=False;",
    "CompanyName": "RecommendationSite1 ",
    "CompanyPhone": "+7 (111) 111-11-11",
    "CompanyPhoneShort": "+71111111111",
    "CompanyEmail": "[email protected]"
  }
}

Method attempting to read that connection string in Startup.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RecommendationSite.Data;
using RecommendationSite.Domain.Repositories.Abstract;
using RecommendationSite.Domain.Repositories.EntityFramework;
using RecommendationSite.Domain;
using RecommendationSite.Service;
using Microsoft.AspNetCore.Identity;

namespace RecommendationSite
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration) => Configuration = configuration;

        // This method gets called by the runtime. Use this method to add services to the container.

        public void ConfigureServices(IServiceCollection services)
        {
            Configuration.Bind("Project", new Config());

            services.AddTransient<ITextFieldsRepository, EFTextFieldsRepository>();
            services.AddTransient<IServiceItemsRepository, EFServiceItemsRepository>();
            services.AddTransient<DataManager>();

            services.AddDbContext<AppDbContext>(x => x.UseSqlServer(Config.ConnectionString));

            services.AddIdentity<IdentityUser, IdentityRole>(opts =>
            {
                opts.User.RequireUniqueEmail = true;
                opts.Password.RequiredLength = 6;
                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireLowercase = false;
                opts.Password.RequireUppercase = false;
                opts.Password.RequireDigit = false;
            }).AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();
          
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name = "myCompanyAuth";
                options.Cookie.HttpOnly = true;
                options.LoginPath = "/account/login";
                options.AccessDeniedPath = "/account/accessdenied";
                options.SlidingExpiration = true;
            });

            services.AddControllersWithViews()
             .SetCompatibilityVersion(CompatibilityVersion.Version_3_0).AddSessionStateTempDataProvider();

            services.AddDbContext<RecommendationSiteContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("RecommendationSiteContext")));
        }

        // 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.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();

            /*var defaultCulture = new CultureInfo("en-US");
            var localizationOptions = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(defaultCulture),
                SupportedCultures = new List<CultureInfo> { defaultCulture },
                SupportedUICultures = new List<CultureInfo> { defaultCulture },
            };

            app.UseRequestLocalization(localizationOptions);

            var ui = System.Globalization.CultureInfo.CurrentUICulture;*/

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

I'm a novice programmer and I'm confused about something, maybe someone knows what the reason is?

I searched all the forums and tried many different variations.

1
  • 1
    ConnectionStrings should be in their own section not inside another section. Look at examples.ù Commented Sep 16, 2023 at 13:51

1 Answer 1

0

The exception "Value cannot be null. Parameter name: connectionString" is likely being thrown by this function: Configuration.GetConnectionString("RecommendationSiteContext"). This is a extension method or a "helper" method which specifically looks for a configuration in your appsettings.json file which starts with this pattern:

"ConnectionStrings": {
  "RecommendationSiteContext": "Data Source=.."}

Since your appsettings.json file does not have that property, it is not finding that section, and then throwing the exception. For example, your connection string is currently stored inside the "Project" JSON object:

 "Project": {
    "ConnectionStrings": "Data Source==(local)\\SQLSERVER; Database=RecommendationSite; ...

So, in order to fix that particular exception, you would need to add a json section and move over your connection string like so:

{
  "Project": {
    "CompanyName": "RecommendationSite1 ",
    "CompanyPhone": "+7 (111) 111-11-11",
    "CompanyPhoneShort": "+71111111111",
    "CompanyEmail": "[email protected]"
  },
  "ConnectionStrings": {
    "RecommendationSiteContext": "Data Source=(local)\\SQLSERVER; Database=RecommendationSite; Persist Security Info=false; User ID='sa'; Password='sa'; MultipleActiveResultSets=True; Trusted_Connection=False;"
  }
}

There is a similar question here, but keep in mind that is using an older version of .NET, so may not translate perfectly. However, the above recommendation should help you. Value cannot be null. Parameter name: connectionString appsettings.json in starter

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.