0

I'm new to ASP NET CORE and I'm writing new web API. I'm not able to retrieve connection string from the appsettings.json file and I get an ArgumentNullException. This is the code in my Startup class:

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

    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDbContext<MyDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDBConnection")));
        ...
    }
}

This is my appsettings.json file:

{
  "ConnectionStrings": {
    "MyDBConnection": "..."
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
       "LogLevel": {
          "Default": "Warning"
       }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

What am I missing?

EDIT: This is also my Program.cs class:

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>();
}
6
  • 1
    Your code looks good to me, the only thing I would change is to call services.AddMvc() after services.AddDbContext (in fact after any other service registration). Commented Feb 27, 2019 at 10:00
  • I put it at the end, after other service registartion, but nothing changes Commented Feb 27, 2019 at 11:47
  • @NicolasP Then there is something wrong in anywhere. Can you give remote access with team viewer so that I can fix this. Commented Feb 27, 2019 at 11:55
  • I think the problem is Directory.GetCurrentDirectory() which might cause issues debug and make sure that the path is the correct one. Commented Feb 27, 2019 at 12:01
  • @AntoniosKatopodis yes, it is. I removed it and now seems that it works, thanks! Commented Feb 27, 2019 at 12:04

1 Answer 1

1

Just to answer this. Directory.GetCurrentDirectory() will get the bin/debug or release location.

This means that it will not be the project location. So it can not find the application.json and also it would also not be able to find your MVC views later on.

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.