4

Just started messing with ASP.NET Core, pretty impressive so far. In the code generated,(see below). I want to change the hardcoded connection string to get it from the appsettings.json file.

This is apparently impossible. I haven't found a single example that works (or even builds).

What's going on?? Please help

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
            optionsBuilder.UseSqlServer("Server=xxxxxxx;Database=xxxxx;Trusted_Connection=True;");
        }
    }

The link provided solves the problem in one area but doesn't work here in OnConfiguring. What am I doing wrong ?

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_1);

        var connection = Configuration.GetConnectionString("ConnectionName");
        services.AddDbContext<SurveyContext>(options => options.UseSqlServer(connection));
    }

    // 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.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
6
  • is this function in your DB context? and what code exactly did you generate? can you provide the steps you took? Commented Oct 30, 2018 at 20:03
  • check this learn.microsoft.com/en-us/aspnet/core/fundamentals/… Commented Oct 30, 2018 at 20:06
  • Nope not my code, generated by VS2017 using Scaffold-DbContext command in package manager window Commented Oct 30, 2018 at 20:06
  • when you use the Scaffold-DbContext option you should be getting a documentation url at the top of your DbContext class. did you check that? Commented Oct 30, 2018 at 20:07
  • for clarity for readers, do update your question saying you used Scaffold-DbContext for code generation Commented Oct 30, 2018 at 20:08

3 Answers 3

2

In the startup class of a .NET Core project you usually register this in the ConfigureServices function.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<YourContext>(options => options.UseSqlServer(connection));
}

When you are in the startup class of a .NET Core it is no problem to read the values from appsettings.json.

You could read more at Microsoft, i.e. here: https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

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

6 Comments

yep did exactly that, put a breakpoint on the line, doesn't even get there
@djack109 Can you show me how your startup-class lookes like and where the startup-class is called? From there I'm sure I can help you
added to my original post
I looked in your code for Startup and can't see any problems instantly from that. But what exactly happens, do you come into ConfigureServices or Configure function? If not I'm pretty sure the problems is outside of the Startup-class. @djack109
Deleted the ConfigureServices I think that was the cause of my problems
|
1

In the place where you want to access the appsettings.json,

JToken jAppSettings = JToken.Parse( 
      File.ReadAllText(Path.Combine(Environment.CurrentDirectory, 
      "appsettings.json")));

Now since you have the object, you can access its contents. Let me know if it works.

10 Comments

if this is what he is trying to do, i would recommend using IConfiguration instead. it is already a json phrased string learn.microsoft.com/en-us/aspnet/core/fundamentals/…
@NevilleNazerane nope, that doesn't help either
@Minu this is the closest I found so far, at least in brongs the contents back. I just need a robust way of getting the contents out :)
the tricky thing about .net core is you need to understand an array of concepts before using it well
This answer might have "worked", but I dont think its the right solution. Like @NevilleNazerane said, you need to use IConfiguration. You will have to make sure its generated correctly and u use the right path to your connection string.
|
1

When you use the Scaffold-DbContext, by default it hard codes your string into the DbContext class (so it works out of the box). You will need to register your DbContext in your startup class to proceed. To set this up, you can check the instructions in this answer.

Note that the Configuration property directly connects to your appsettings.json and several other locations. You can read more about it in this documentation. While you can always use the appsettings.json file, it is generally recommended to have your secure secrets in an external json file outside your source code. The best solution for this during development is using the secret manager. The easiest way to use this is right click on your project on visual studio and select "manage user secrets". This will open a json file that is already connected to your Configuration object.

Once this is set up, you need to use dependency injection to access your db context.

public class HomeController : Controller
{


     public HomeController(SurveyContext context)
     {
         // you can set the context you get here as a property or field
         // you can use visual studio's shortcut ctrl + . when the cursor is on "context"

         // you can then use the context variable inside your actions
     }
}

When you use using, it creates a new connection each time. Using injection makes sure only one connection is created per request no matter how many times it is used.

7 Comments

Yep tried that too, as per the documentation. The code in StartUp.cs doesn't even get touched.
doesn't get touched? how are you using your DbContext?
in a using statement just like I have done for years with EF using (var context = new SurveyContext())
once you have startup setup, you need to use your Db Context with dependency injections not using. check that link again, I will update my answer with how you need to use your db context
I don't see in your answer where you are using DI in the controller to get at the data as opposed to a using statement
|

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.