1. Overview
The ASP. NET 5 Template project configuration file is in JSON format, and you can still use the previous XML format. C # has a special class for Web. config or app. config read-write and encryption, which is convenient to use.
By using Config.json To configure the information, is C # ready for a class? Hey! Play dotnet technical content is low, by the Java experts despise reason, perhaps it is so, Microsoft want to help everyone write well, you just need to use can.
2. Create a project
This example uses the ASP. NET 5 template to create the console project:
3. Configuration files
Add Config.jsonto the Givecase.consoleapps project Root, whose code:
{ "Data": { "mssqlconnection": { "ConnectionString":"server= (localdb) \\mssqllocaldb;database=testdb; Trusted_connection=true; Multipleactiveresultsets=true" } }/*, "EntityFramework": {"Efcontext": {"ConnectionString": "Data:MSSqlConnection:ConnectionString" } }*/}
Note: The JSON key follows "data->mssqlconnection->connectionstring" to find values!
4. References
Open Project.json, add:
5. Code implementation
The following changes are read before and after the modified output:
usingMicrosoft.Framework.ConfigurationModel;usingSystem;namespacegivecase.consoleapps{ Public classProgram { PublicIConfiguration Configuration {Get;Set; } Public voidMain (string[] args) { #region01 read-Write database connection stringConfiguration=NewConfiguration (). Addjsonfile ("Config.json"); stringStrkey ="Data:MSSqlConnection:ConnectionString"; stringConnStr =Configuration.get (strkey); //Read before modificationConsole.WriteLine (CONNSTR); Configuration.set (strkey,"server=.; Database=givecasetestdb; Uid=sa; pwd=123456"); Configuration.commit (); ConnStr=Configuration.get (strkey); //Read after modificationConsole.WriteLine (CONNSTR); #endregionConsole.ReadLine (); } }}
Operation Result:
Then look at the Config.json code:
Ok! can be modified successfully!
6. Summary
Read and write on the above, if you want to write encryption string, reading and re-program decryption, you have to "study"!
(Note: The content of this article is small, I hope you all help!) The following series of blog posts are also every knowledge point to publish an article! )
No. 03. ASP. NET 5: Read and write database connection strings