How to Read The appsettings.json Configuration File in ASP.NET Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
asp.net core allows you to set up a configuration file that can be read in your application by default the app settings json file is read from the application and you can use the settings within it in this video we're going to show you some of the different ways where you can actually read this file in addition we'll show you how to validate a particular configuration how to set up database connection strings and how to add app settings into a console application now for more asp.net core coding tutorials visit roundthecode.com subscribe to our youtube channel at slash round the youtube.comco and follow us on twitter it's at round the code join the round the code discord server ask your asp.net call question and get our community to help solve your issue go to roundthecode.com forward slash discord so to demonstrate how to read a configuration file into an asp.net core application we're going to go ahead and create a new asp.net core mvc application i've got visual studio open in front of me so let's go ahead and create a new project so we're going to select asp.net core web application we're going to stick it inside around the code.app settings and we're going to call it round the code app settings dot web go ahead and create that we need to select asp.net core web app model view controller and that's creating our application for us okay so our application is set up so we're just going to go ahead and test it first of all we're going to point it to localhost colon 5000 in order to do that we need to right click on the application on the project and click on properties okay so that's loaded up for us so let's go down to debug and in launch we're going to scroll down to project i'm going to untick the launch browser and the app url we're going to point it to localhost colon 5000 and go ahead and save that let's now run our application and make sure that it's working okay so our application is running let's just check that it's going to work in a browser so we've got localhost colon 5000 here and as you can see our test application is working that's ready for us now to actually read the actual settings from the configuration file so now we're going to go about setting up custom configuration so now that we've got the asp.net core npc application we're going to have a look at the app settings so this now uses a json file if you familiar with asp.net applications you remember you have a config file which is an xml file the nice thing about json is that you don't have these really long tags and you don't have schemas either so it's a lot more lightweight and compact now what we're going to do in here is we're going to create our own custom configuration we're going to call it round the code sync and inside that we're going to create a couple of different so we're going to create a title property we're going to put the label as our sync tool we're going to create an interval and we're going to set that to 30 minutes that's going to be a time span lastly we're going to set a concurrence threads property and we're going to put a value of 10 in there so there's three different ways that i'm going to show you how to read the actual app settings file into our application now the first way is just to actually bring in the configuration and read it so what we're going to do is we're going to create a new controller we're going to call it app settings controller so that's set up for us what we're going to do now is we're going to bring in the eye configuration instance so we'll bring it in through dependency injection so first of all we're gonna declare it inside the controller now we're going to set up the constructor and we're going to pass the configuration which we've got from dependency injection like so the first things first we're going to read directly from this configuration instance so what i'm going to do is i'm going to set up a new action i'm going to call it first way and up here we're going to set a root of first way we're also going to set a root in the controller and we're going to point that to app settings so quite simply what we do is we're going to return the content type and this is one way where we can actually read the configuration a setting from the configuration we've got our configuration instance we can call get section around the code sync so that's this section here there we can call the get children method then we can call the first or default method we use the config so we can find the first config that has a key of title so in this instance here it would be this one here all we need to do after that is to pass the value in and we just need to pass back a mime type of text plane that's one way of doing it but it's quite long-winded another way you can do it which is a lot simpler is if we go onto a new line we can just quite simply call underscore configuration dot get value we know it's a type of string we pass that in and then we can pass in around the code sync with the colon and title so what we're going to do now is we're going to run the application and just make sure that the values are shown the values should be our sync tool so we should have two instances of that so as you can see there we've got our two instances there now that's all very good as well but what if we want to sort of validate the configuration or what if we want to bind it into a strongly typed class well we're going to go ahead and do that now and there's two ways we can go about doing this so the first what we need to do first is we need to create a class which represents the round the code sync in our app settings we're going to create a new folder inside here we're going to create a new interface i'm going to call it i round the code sync so what we're going to do with this is we're going to copy what's in the app settings file so we're going to have a title and interval and the concurrent threads and we're also going to set the types for each property so for the title we're going to set it as a string we're going to use a time span for the interval and finally for the concurrent threads we're going to use an integer now we're going to go ahead and actually create the class for this around the code sync recreate a new item select class and call it round the code sync i'm going to go ahead and copy these properties into there and we just need to make all of them public okay so the first way of demonstrating this is we're going to use the options pattern so we have to go into our startup class and inside that we call our services instance and we can call add options and we need to pass in the type which is around the code sync we also need to bring in the reference for that from there then we can bind it to our app settings so we do that through configuration dot get section around the code sync so that's all our settings set up our configuration setup we now need to output that that actual instance of the glass into our controller so what we can do is we can bring the options pattern into our app settings controller through dependency injection now in order to do that once again we'll create an instance for the controller so we're passing the i options interface and within that we need to specify a generic type which we're going to call rather code sync so the class that we just set up with our configurations in it i'm going to call that unscore around the code sync options now we're going to bring this into our constructor and we're going to declare it with the same value we're passing in through dependency injection into our instance in the controller now that we've done that we're going to create a new route i'm going to call it second away and a new action and once again we're going to demonstrate how to actually output the value of title from the round the code sync but this time we're going to do it through the options pattern rather than using the configuration instance so quite simply with that we return the content again and all we need to do here is we need to call our instance of underscore around the code think options use the dot value and then we can just either pass in the title the interview interval or the concurrent threads we're going to select title so let's go ahead and run that and see if it's actually going to work for us as you can see on the screen that's now working for us now there is another way i'm going to show you on how to actually read that file so if we make a stop to that so we don't need to include it in the options pattern we can actually read the eye around the code sync interface directly now if we go back into our startup the way that we can do this is we can add a singleton and within that singleton we pass in what will be an instance of i round the code sync which will represent the roundness code sync class so with a single turn you can use a delicate and that's what we're going to do here we have to pass in an instance here of service provider which is iservice provider type and in here we can return the configuration so we get the configuration from here get section as you can see it's similar to what's going on here and the only difference is we need to call the get method and this will now bind it into our round the code sync type like so and what we need to do just before we run this is we need to make sure that the around the code sync has ref has an interface of eye around the code sync otherwise it's not going to work as you can see we haven't got any errors now so we can go back into our controller and once again what we're going to do with this is we're going to create a new action we're going to call it third way but before we do that we need to pass in our instance of i ran the code sync remember we've already set this up now as a singleton so we should be able to pass it in as a parameter into the constructor okay then it should just be a simple case passing in on school around the coat sink and passing in the title but before we do that we need to make sure that we pass that in as public and that will fix our error for us so let's go ahead now and run our application as you can see we're also able to output the settings directly through the actual instance of the configuration so the next thing i want to talk to you about is validating configuration now what we can do is because we've created a strongly typed class for our settings we can go ahead and use data annotations so we're going to go ahead and do that now so for the title we actually want to declare that we require to have a value for it and with the concurrent thread we want it between a particular range of 5 to 15. so anything outside below 5 or higher than 15 will throw an error for us now we're going to go into our app settings file here and we're going to change some of these settings so we're going to get rid of our title and we're going to change the concurrent threads now this on its own will not actually validate it we need to make a change in our startup so we're going to try it for the second way so using the options pattern and quite simply with this we can just call validate data annotations so we're going to go run our application now and see if it actually causes an error or not so as you can see on the screen here we've got our errors here so we've got data validation failed for members title with the error the title field is required and the same for concurrent threads the field concurrent threads must be between 5 and 15. let's go ahead and put that back to how it was and let's rerun it again and see if it actually runs for us you can see no issues this time it's managed to run for us now with our other way so directly bringing in the eye around the coats interface we need to make some changes in the startup as well so first of all we're going to remove the validate data annotations so it doesn't conflict so that's from our options pattern and what we're going to do now is we're going to go to our singleton i'm going to take this away and we're going to store this into a variable of config next we need to know it needs to validate against the data annotations and in order to do that you can use the validator class we need to bring in the reference for that and then we can call the try validate object we pass in our instance of the config we need to create a new validation context instance once again we bring in our instance of the config and this is just what this does is it lists all the errors we're not going to be outputting this at all so we're just going to create a new list instance in here but not set it to a particular variable so a new list of validation result and this validate all properties if this is set to false then it will only validate attributes that are required we need to set this to true fix the error there now if valid is set to false what we can do now is we can set up our own exception so we're going to go ahead and do that so if it's not valid we throw a new exception if i can spell properly not all the settings are valid assuming everything's fine we just return our instance of config now once again we're going to demonstrate that so we're going to remove the title and we're going to set the concurrent threads to 18 run our application and see what happens record the url there and we've got our error we've got our exception here so you can see here it says not all the settings are valid let's go ahead and put the app settings back to how it was run the application again i'm going to refresh this and as you can see our configuration is now working for us so the next thing i want to do is to create a separate configuration file now this is handy if you have a large application with lots of settings you can separate it out into individual files so in order to do this what we do is we create a new file add new item and what we want to do is we want to create a new json file we're going to call it round the code sync we take that out what we're going to do is if we go into our app settings we're going to take this out of appsettings.json and we're going to put it in here we also need to make sure this normally does it automatically but we still need to make sure that we set the build action to content and the copy to output directory as copy if newer if this is set to do not copy it's not going to copy the file when we actually build the application so it won't be able to read the application and it will almost certainly either not read the file or it will throw an error but that's all good now to set this up we need to go back into our startup class now we don't we need to go into our program class that's what we need to do now in here we can call a method which is called configure app configuration what we need to do now is we need to specify this extra file into our instance of host so in here we can pass in two parameters hosting context and config [Applause] i'm quite think simply our instance of config this is a instance of i configuration builder in here there's an add json file method so we're going to specify our around the code sync.json i'm going to make it optional it's not mandatory and reload on change we're going to set that to true as well all right with that going let's run it in our application let's run our application and see if it loads up in our browser okay so our application is running now so let's load it up you can see it's working with our second way let's try it with the third way so directly through the eye around the code sync instance and as you can see that is working for us in a separate file so now i'm going to show you how to import connection strings configuration now in front of me i've created this round the code sync database go into dbo.sync in here it's just got an id and a name of around the code sync we're now going to use that and we're going to import it into our application so what we need to do first is we need to declare the connection string so in order to do that we use the connection strings key and then we're gonna give it a name of sync db and this is where we place our connection string so the server is localhost the database is around the code sync use a trusted connection multiple active set result sets let's set that to true and bring this over a bit for you so you can see and then integrated security we're going to set to true so that's now set up for us what we need to do now is we need to install a new get package go into tools new get package manager run the install package command and we need to bring down system.data.sql client now that's done we're going to go into our app settings controller and we're going to create a new action and make it asynchronous and bring back ask of all right action result and we're going to call it database i'm going to set up a root for it as well and we're going to call that database well so what we're going to do is we're going to create a variable of name going to make it empty at first we set up a new connection string create a new instance of sql connection so inside the sql connection one of the parameters is the connection string which we've just set so in order to get that we use our configure our underscore configuration instance which is up here and quite simply we call the get connection string method and we specify sync db now this sync db we go back into our app settings that is our connection string here so it's just representing what's in our app settings now we need to open our connection and we're going to run a sql command so to do that i'm going to create a new instance of sql command i'm going to run select star from dbo dot sync we go back into our database that's this table here where id equals one and we need to pass in our connection over a bit for you now we're going to create a new data reader so we can actually read the value and i call execute reader async and we call await reader.read async so it's now reading the values from our actual command we can set the name from our reader and obviously name is the column name for it and we just need to declare it as a string and finally what we need to do is just return that name of the content type so we're going to pass in the mind type of text plane okay let's give that a run and see if we're getting that value back in our browser so as you can see it's returning our value from our database so we've got around the code sync there and as you can see it's the same value in our database next thing i want to do is to show you how to use app settings in a console application and once again we've got visual studio open in front of us and we need to go ahead and create a new project so for this one we're going to select console app.net core now we're going to make sure it's in around the code app settings and we're going to call it around the code.app settings.console app that's now going ahead and creating our application for us okay so that's set up for us we just need to make sure that we've set it to net five so that's loading up for us so yeah it's on.net core 3.1 let's just change that to net 5. okay so we're now going to go ahead and create our app settings file so we'll select select javascript json configuration file we're going to call it app settings now one thing to bear in mind when you do this with a console application the build action and the copy to output directory are none and do not copy we want to set set the build action to content and the copy to output directory to copy if newer that will now make sure that our app settings is built is copied over when the console application is built and when it's running now we're going to set up our app settings file once again we're going to bring in around the code sync and we're going to pass in the title again our sync tool the interval and the concurrent threads now in order to make this work in the console application we need to bring in some nougat packages there's a number of these we need to install the first one is microsoft extensions dot configuration we also need to bring in microsoft.extension.configuration.json and we also need to bring in binder as well bring that down there we also need to bring in microsoft.extensions and finally we need to bring in the newton soft.json package okay that that's all done for us let's now go ahead and create our config files again so this is copying what we did with our asp.net core mvc application so we're going to create a new instance again go up here call it interface even i run the code sync make sure it's public this time and we're going to pass in the title the interval as a time span and finally the concurrent threads now we're going to create our class pull it around the code sync and pass those properties in and make sure they're all public now that we've got that all set up we go into our console application here what we need to do is we need to create a new instance of our config so we call a new instance of the configuration builder if you're doing this in asp.net core we already have an instance of configuration builder but with a console application or if you're using testing or anything like that you'll need to create a new instance of it go ahead and do that we add our json file which we've called app settings.json if you wanted that to be a different file name you can do and just call build now from there we've got our instance of config so what we can do is we can set up round the code sync so once again we call our config get section this is very similar to how we did it with our asp.net core application get section and then we call the get method and we pass in around the code sync that will bind around the code sync settings into our around the code sync class now like with an asp.net core application we can use our validator class to make sure that we can validate it against particular data annotations like requiring the title or having the concurrent threads in a particular range so once again we call our validator class we need to bring in the reference for that try validate object around the code sync new validation context passing in around the code sync again there's and then pass in a new instance of validation result as a list and set validate all properties to like so and if we can't validate it we're gonna just throw an exception unable to find all settings now that's done we're just going to output to the console each of the settings so we're going to call around the code title do the same for interval and do the same for concurrent threads and do a read key here now run the application and make sure that it's working we've got an error there where's the error i guess we need to bring in the reference for list run that again so you can see there is output in our settings what we need to do now is stop that we need to make sure that our validation's working so we'll get rid of the title and we'll set the concurrent threads to 18. let's run our console application again and you can see that's running because we didn't actually add our data annotation so let's go ahead and do that set the title to required and set the concurrent threads to a range of 5 and 15. let's run that again and see if we're going to get an error or not as you can see there it's throwing our exception so the validator is working in our console application so that's how you get going with asp.net cores configuration it's good that you're able to bind the settings into a strongly typed class and be able to validate them in addition it's also good that we're able to separate each group of settings into separate files and into separate classes this makes it ideal whether you're writing a small application or a large application thanks very much for watching and hit a like on the video
Info
Channel: Round The Code
Views: 1,054
Rating: undefined out of 5
Keywords: appsettings.json, asp.net core appsettings, appsettings, .net appsettings, .net appsettings.json, asp.net core appsettings.json, .net core appsettings, .net core appsettings.json, .net 5 appsettings, .net 5 appsettings.json, asp.net core configuration, .net configuration, .net core configuration, appsettings validate, appsettings.json validate, appsettings connection string, appsettings sql server, appsettings.json connection string, appsettings.json sql server
Id: PN6kAaZVVBM
Channel Id: undefined
Length: 37min 14sec (2234 seconds)
Published: Sun Mar 14 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.