我们有一些遗留的4.5.2类库,它们共同使用ConfigurationManager.AppSettings [key]
是否可以在.net core 2应用程序中引用这些内容,以便在引擎盖下正确修补配置?
即旧的调用ConfigurationManager.AppSettings [key]正确地从json或xml读取配置,但是在.netcore2应用程序中.
如果我将问题的键移植到appSettings.json,那么对ConfigurationManager.AppSettings的调用总是返回null.
一个例子是:
- {
- "Logging": {
- "IncludeScopes": false,"Debug": {
- "LogLevel": {
- "Default": "Warning"
- }
- },"Console": {
- "LogLevel": {
- "Default": "Warning"
- }
- }
- },"appSettings": {"test": "bo"},"test": "hi"
- }
然后:
- [HttpGet]
- public IEnumerable<string> Get()
- {
- return new string[] { "value1","value2",ConfigurationManager.AppSettings["test"],ConfigurationManager.AppSettings["appSettings:test"] };
- }
将显示:
- ["value1",null,null]
解决方法
您正在寻找的设置是可能的,设置可以保存在app.config中.
我有一个.NET 4.5.2类库“MyLibrary”和一个.NET Core 2.0 Web应用程序“WebApp”引用完整的.NET框架4.6.1.
我的图书馆
>具有System.Configuration的程序集引用
>有一个类Foo,它用键foo读取appsetting
Web应用程序
>有MyLibrary的项目参考
>具有System.Configuration的程序集引用
>有一个包含appSettings部分的app.config文件. (默认情况下,App.config存在于.NET Core 2.0 Web应用程序项目中.)
>在Foo实例中使用,调用其GetSomething方法,通过该方法将值栏分配给变量.
所有其他文件和设置都是默认值.以下是上面提到的那些.
MyLibrary项目
.NET 4.5.2
Foo.cs
- using System;
- using System.Configuration;
- namespace PFX
- {
- public class Foo
- {
- public String GetSomething()
- {
- String r = ConfigurationManager.AppSettings["foo"];
- return r;
- }
- }
- }
WebApp项目
.NET Core 2.0.1引用完整的.NET框架4.6.1.
WebApp.csproj
- <Project Sdk="Microsoft.NET.Sdk.Web">
- <PropertyGroup>
- <TargetFramework>net461</TargetFramework>
- </PropertyGroup>
- <ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore" Version="2.0.3" />
- <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.4" />
- <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.0.4" PrivateAssets="All" />
- <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.3" />
- <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.0.3" />
- </ItemGroup>
- <ItemGroup>
- <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\MyLibrary\MyLibrary.csproj" />
- </ItemGroup>
- <ItemGroup>
- <Reference Include="System.Configuration" />
- </ItemGroup>
- </Project>
App.config中
- <configuration>
- <runtime>
- <gcServer enabled="true"/>
- </runtime>
- <appSettings>
- <add key="foo" value="bar"/>
- </appSettings>
- </configuration>
Program.cs中
- using System;
- using Microsoft.AspNetCore;
- using Microsoft.AspNetCore.Hosting;
- namespace WebApp
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- PFX.Foo foo = new PFX.Foo();
- String someting = foo.GetSomething(); // bar
- BuildWebHost(args).Run();
- }
- public static IWebHost BuildWebHost(String[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .UseStartup<Startup>()
- .Build();
- }
- }