0

I've been developing a web-application with ASP.Net Core MVC using C# and Entity Framework Core to interact with a SQL Database running on SQL Server 2017.

The application is now in Staging, but I'm running into problems. In the application properties, I change the ASPNETCORE_ENVIRONMENT variable from Development to Staging. Now that it's changed to Staging, the application throws many errors. But, if I switch it back to Development, it runs as normal.

I get the following errors when running the application with a Staging variable:

Error when moving into the Staging Environment

I use Entity Framework Core Database-first approach to automatically generate the database entities and their fields (e.g. SuspicioiusTypeID, BayID, etc). A solution I found related to the error doesn't capture my problem. My error only occurs when I'm in an environment other than Development.

What causes this error and how can I fix it?

Startup, ConfigureServices, and Configure:

public class Startup
{
    public static string ConnectionString { get; set; }
    public static NICSContext Context { get; set; }
    public static string version;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        ConnectionString = Configuration.GetConnectionString("DefaultConnection");
        version = Configuration["Version"];

        DbContextOptionsBuilder <NICSContext> optionBuilder = new DbContextOptionsBuilder<NICSContext>();
        optionBuilder.UseSqlServer(ConnectionString);
        Context = new NICSContext(optionBuilder.Options);
    }

    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.AddDbContext<NICSContext>(options =>
            options.UseSqlServer(ConnectionString));

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => {
            options.LoginPath = "/Login";
        });

        // Repository Interfaces
        // REMOVED FOR CLARITY AND PROPRIETARY PURPOSES 

        // Service Interfaces
        // REMOVED FOR CLARITY AND PROPRIETARY PURPOSES 

        services.AddMvc(options => {
            // Default policy - Authorize
            var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        });

        services.AddDistributedMemoryCache();
        services.AddSession();

        // Singletons
        services.AddSingleton(new MapperService().Mapper);
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
            app.UseDatabaseErrorPage();
        }

        if (env.IsStaging() || env.IsProduction())
        {
            app.UseExceptionHandler("/Error");
        }

        app.UseFileServer();
        app.UseSession(); 
        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Dashboard}/{action=Index}/{id?}");
        });
    }
Corey P
  • 955
  • 1
  • 14
  • 23
  • Can you make sure your database schema is up to date in Dev and Staging environment? – Muheeb Sep 20 '18 at 14:01
  • Hi @Muheeb! I verified that the schemas are inline. I also rescaffolded to ensure my C# classes were up to date. Both look good. – Corey P Sep 20 '18 at 14:12
  • 1
    do you have separate appsettings.config for staging environment(appsettings.Staging.json)? check connection string if it is pointing to right database? – Muheeb Sep 20 '18 at 14:27
  • @Muheeb I don't have a separate appsetting.config file (i.e. appsettings.Staging.json), could that be the issue? I am using the correct connection string, but it comes form appsetting.config. – Corey P Sep 20 '18 at 14:30
  • No. If you dont have that then it will use your appsettings.json file. Can you share your startup.cs ? – Muheeb Sep 20 '18 at 14:35
  • @Muheeb Added the startup.cs. – Corey P Sep 20 '18 at 14:42

2 Answers2

1

I found out the error. I had set my default connection in secret.json pointing to our centralized database, but the appsettings.json default connection pointed to the local database (which hadn't been updated in months). Once I set the default connection in appsettings.json to point to our centralized database, it fixed the problem.

Explaination:

When the ASPNETCORE_ENVIRONMENT variable is set to Development, ASP.Net Core looks in the User Secrets file (i.e. secrets.json) for the connection string before looking in the appsettings.json file.

However, when ASPNETCORE_ENVIRONMENT is set to something else, ASP.Net Core no longer looks in the User Secrets file for the connection string, but instead the appsettings.json file.

Corey P
  • 955
  • 1
  • 14
  • 23
0

I am not sure if it makes a difference, In my project I have added dbcontext to pipeline this way. Do you want to try?

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddEntityFrameworkSqlServer().
           AddDbContext<NICSContext>(options =>
           options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }
Muheeb
  • 216
  • 2
  • 6