1

Looking for some insight into this issue. To me, it looks like all the configuration aligns with what is expected, but whenever i try to run dotnet publish TestAPI.dll and attempt to hit an endpoint, I see the following:

ArgumentNullException: Value cannot be null. Parameter name: connectionString Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(string value, string parameterName) Microsoft.EntityFrameworkCore.Infrastructure.RelationalOptionsExtension.WithConnectionString(string connectionString) Microsoft.EntityFrameworkCore.MySQLDbContextOptionsExtensions.UseMySQL(DbContextOptionsBuilder optionsBuilder, string connectionString, Action MySQLOptionsAction) TestAPI.Startup.b__4_0(DbContextOptionsBuilder options) in Startup.cs + options.UseMySQL(Configuration.GetConnectionString("DefaultConnection"))); Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions+<>c__DisplayClass0_0.b__0(IServiceProvider p, DbContextOptionsBuilder b) Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory(IServiceProvider applicationServiceProvider, Action optionsAction) Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions+<>c__DisplayClass5_0.b__0(IServiceProvider p) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProvider provider) Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(IServiceCallSite callSite, TArgument argument)

I can confirm that it's working as expected when I run the application from the IDE (Visual Studio for Mac). Here's my relevant config:

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;userid=root;pwd=root;port=3306;database=Expenses;sslmode=none;"
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    //"Console": {
    //  "LogLevel": {
    //    "Default": "Warning"
    //  }
    //}
  }
}

appsettings.Development.json

{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;userid=root;pwd=root;port=3306;database=Expenses;sslmode=none;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TestAPI.Data;
using TestAPI.Data.Models;
using System;
using Microsoft.Extensions.Logging;

namespace TestAPI
{
    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.AddCors();

            services.AddMvc();

            services.AddDbContext<ExpensesDbContext>(options =>
                                                    options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
            services.AddTransient<IBaseDa<Accounts>, AccountsDataAccess>();
            services.AddTransient<IExpensesDa, ExpensesDa>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            env.EnvironmentName = "Development";

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder => builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());

            app.UseMvc();
        }
    }
}

Program.cs

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace TestAPI
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //var builder = new ContainerBuilder();

            //// register types here for DI
            //builder.RegisterType<AccountsDataAccess>().As<IBaseDa<Accounts>>();

            //_container = builder.Build();

            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}

even tried editing the appsettings.Development.json and appsettings.json within the corresponding publish folder (e.g. bin/Release/netcoreapp2.0/publish)

Any help is greatly appreciated! Thanks all

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Steve Boniface
  • 571
  • 1
  • 11
  • 23
  • Are you adding the JSON files to IConfiguration from the program.cs file? – Jason H Jun 16 '18 at 19:06
  • @JasonH No. It's working when I run the application from VS, though. I'll edit to share my Program.cs code – Steve Boniface Jun 16 '18 at 19:09
  • I have never tried to run an ASP.NET Core Project without configuring the appsettings.json load process...maybe VS is doing some 'magic' under the sheets that I never knew it did. Let me get you the code I think you need to add and give it a go... – Jason H Jun 16 '18 at 19:13
  • It's unclear how do you publish your app. Is this `dotnet publish` and then `dotnet TestAPI.dll` ? – xneg Jun 16 '18 at 19:28
  • @xneg Yes. `dotnet publish --configuration Debug` or `dotnet publish --configuration Release` (tried both). Then, after having navigated to the output directory from the CLI, I execute `dotnet TestAPI.dll`. This launches the app on localhost on the port I configured. When trying to hit an endpoint, I see the error I've described above. – Steve Boniface Jun 16 '18 at 19:30
  • That's strange. I just tried to publish with both configurations and it works for me... At least it writes config info. Try `Console.WriteLine(Configuration.GetConnectionString("DefaultConnection"));` in your `ConfigureServices` to insure your app doesn't see config. – xneg Jun 16 '18 at 19:44
  • @xneg. yes, as you/we predicted, i confirmed it is not seeing any Sections in appsettings.json. its not seeing my ConnectionStrings or Logging sections – Steve Boniface Jun 16 '18 at 21:11
  • @SteveBoniface then I suggest you create a new web project with `dotnet new webapi`, publish it and see if configuration is available. – xneg Jun 17 '18 at 07:08

1 Answers1

0

Try this and if does not work let me know.

startup.cs

namespace TestAPI
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
                Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        .
        .
        .
        .
        .

    }
}
Jason H
  • 4,996
  • 6
  • 27
  • 49
  • According to the [docs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/index?view=aspnetcore-2.1&tabs=basicconfiguration) he already has this because he's using the `CreateDefaultBuilder` when setting up the `WebHost` in `Program.cs` – fredrik Jun 16 '18 at 19:43
  • That would be the 'magic' I was speaking of that I did not know about. I still question if something is not wiring up correctly though. I have a similar issue were when running in 'debug mode' everything was fine but the moment I tried to run in Azure, the code could not locate the Appsettings.json file. – Jason H Jun 16 '18 at 19:56
  • @JasonH tried your suggestion. its still not seeing appsettings.json. i confirmed its not seeing other sections in the config, too (e.g. the Logging section's `.Value` is coming back with a null value). – Steve Boniface Jun 16 '18 at 21:13
  • Which means its not loading up the JSON file. When you publish, is the appsettings.json being moved into the BIN folder or is it staying at the root? – Jason H Jun 16 '18 at 21:37