1.项目中添加App.config文件
因为.NET Core的项目本质是控制台应用,所以ConfigurationManager的API会去默认读取app.config配置文件,而不是web.config配置文件。
2.如果是asp.net迁移过来的配置文件,去除config中和需要的配置无关的内容,主要是<system.web>
、 <system.webServer>
、<system.codedom>
等典型asp.net标签。
<?xml version="1.0" encoding="utf-8"?>
<configuration> <!-- To customize the asp.net core module uncomment and edit the following section.
For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
<!--
<system.webServer>
<handlers>
<remove name="aspNetCore"/>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
--> <appSettings>
<add key="Email" value="1037134@qq.com" />
</appSettings> <connectionStrings>
<add name="TestCon" connectionString="Data Source=.;Initial Catalog=OWNDB;user id=sa;pwd=123456" />
</connectionStrings> </configuration>
3.引入【 System.Configuration.ConfigurationManager 】NUGET包
4.读取
var email = System.Configuration.ConfigurationManager.AppSettings["Email"]; var conn = System.Configuration.ConfigurationManager.ConnectionStrings["TestCon"];