Lots of posts here on how to do this, but no matter what configuration I try, I can't seem to get my database connection string. The startup.cs is configured from the Microsoft project template for Core 2.2 automatically, and as far as I can tell there is nothing wrong with it. I'm not using EF nor do I wish to load some 3rd party black box to get this to work.
Here's the Startup.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace TestWebApplication1
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Here's the appsettings.json file:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=mydbserver;Initial Catalog=mydatabase;Integrated Security=True;Persist Security Info=False;"
}
}
From another post, the following SHOULD work, but it does not:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TestAppWithService
{
public class TestDB
{
string conString = Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString(this.Configuration, "DefaultConnection");
}
}
The file, called TestDB.cs is set to compile and, for kicks, I put it in the root folder (doesn't matter where I put the class: model, controller, etc) I get the Keyword 'this' is not available in the current context. (with a squiggly line under it). I have no idea how to proceed or what to look for and the answers here are numerous with all sorts of tweaks, but as per MS, this should work fine. I'm new to dotnetcore and thought I had this dependency injection stuff figured out, but am still stuck.