Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在.Net Core AppSettings/configuration中处理带句点的键名_C#_Asp.net Core_.net Core - Fatal编程技术网

C# 在.Net Core AppSettings/configuration中处理带句点的键名

C# 在.Net Core AppSettings/configuration中处理带句点的键名,c#,asp.net-core,.net-core,C#,Asp.net Core,.net Core,考虑以下appsettings.json: { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "NumberOfRetries": 5, "Option1": "abc",

考虑以下
appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

  "NumberOfRetries": 5,
  "Option1": "abc",
  "Option2":  "def"

}
要读取
NumberOfRetries
,可以成功使用以下类:

public class AppSettings
{
    public int NumberOfRetries { get; set; }
    public string Option1 { get; set; }
    public string Option2 { get; set; }
}
在Startup.cs中使用以下代码:

    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.AddControllers();

        services.AddOptions();

        services.Configure<AppSettings>(Configuration);
    }
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。使用此方法向容器中添加服务。
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
services.AddOptions();
服务。配置(配置);
}

现在,假设键名是“代码>编号”。重试< /代码>而不是<代码>编号重试< /代码> -中间有周期。


如何修改
AppSetings
类(或方法本身)以支持这一点?无法在属性名中精确地添加句点。

我明白您的意思,我快速查找了一下,可以提供有关选项配置方式的自定义逻辑。我做了一个快速原型

void Main()
{
字符串json=@”{
“”日志记录“”:{
“日志级别”:{
“默认值”:“信息”,
“Microsoft”:“警告”,
“Microsoft.Hosting.Lifetime”“:”“信息”
}
},
“AllowedHosts”“:”“*”,
“重试次数”:5
}";
使用(var doc=System.Text.Json.JsonDocument.Parse(Json,新的JsonDocumentOptions{AllowTrailingCommas=true,CommentHandling=jsoncommmenthandling.Skip}))
{
使用(var stream=new MemoryStream())
{
使用(var writer=newutf8jsonwriter(流))
{
书面文件(作者);
writer.Flush();
}       
流位置=0;
//这里有可用的代码
IConfigurationRoot configuration=new ConfigurationBuilder().AddJsonStream(stream.Build();
var services=newservicecolection();
services.AddOptions();
//如果不符合约定,可以在此处手动配置
服务。配置((选项)=>
{
options.NumberOfRetries=configuration.GetValue(“重试次数”);
});
var container=services.BuildServiceProvider();
使用(var scope=container.CreateScope())
{
var appSettings=scope.ServiceProvider.GetRequiredService();
Console.WriteLine(appSettings.Value.NumberOfRetries);
}
}
}
}
公共类应用程序设置
{
公共int NumberOfRetries{get;set;}
}  
如果您有特定的设置模式,您可以为自己的“约定”创建自定义设置绑定器,我提供了一个非常基本的示例,用于处理设置中的“.”


void Main()
{
字符串json=@”{
“”日志记录“”:{
“日志级别”:{
“默认值”:“信息”,
“Microsoft”:“警告”,
“Microsoft.Hosting.Lifetime”“:”“信息”
}
},
“AllowedHosts”“:”“*”,
“重试次数”:5
}";
使用(var doc=System.Text.Json.JsonDocument.Parse(Json,新的JsonDocumentOptions{AllowTrailingCommas=true,CommentHandling=jsoncommmenthandling.Skip}))
{
使用(var stream=new MemoryStream())
{
使用(var writer=newutf8jsonwriter(流))
{
书面文件(作者);
writer.Flush();
}       
流位置=0;
//这里有可用的代码
IConfigurationRoot configuration=new ConfigurationBuilder().AddJsonStream(stream.Build();
var services=newservicecolection();
services.AddOptions();
services.AddSingleton(配置);
services.ConfigureOptions();
var container=services.BuildServiceProvider();
使用(var scope=container.CreateScope())
{
var appSettings=scope.ServiceProvider.GetRequiredService();
Console.WriteLine(应用设置);
}
}
}
}
公共类应用程序设置
{
公共int NumberOfRetries{get;set;}
}
公共类CustomConfigureOptions:IConfigureOptions
{
专用只读IConfiguration配置;
公共自定义配置选项(IConfiguration配置)
{
this.configuration=配置;
}
公共无效配置(应用设置选项)
{
foreach(configuration.AsEnumerable()中的变量对)
{
foreach(typeof(AppSettings).GetProperties()中的var属性)
{
if(property.Name.Equals(pair.Key.Replace(“.”,”))
{
SetValue(选项、配置、GetValue(property.PropertyType、pair.Key));
}
}
}
}
}
好的,我想出来了

理想情况下,我只想像这样使用
JsonPropertyName

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace WebAPICore
{
    public class AppSettings
    {
        [JsonPropertyName("Number.Of.Retries")]
        public int NumberOfRetries { get; set; }
        public string Option1 { get; set; }
        public string Option2 { get; set; }
    }
}
    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.AddControllers();

        services.AddOptions();

        services.Configure<AppSettings>(Configuration); // This maps every key that matches existing property name

        services.PostConfigure<AppSettings>(appSettings =>// This maps keys where names don't match existing property names
        {
            appSettings.NumberOfRetries = Configuration.GetValue<int>("Number.Of.Retries");
        }); 
    }
但它不起作用。为什么?他们没有为此使用JSON解析器吗

因此,我最终得到的解决方案如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace WebAPICore
{
    public class AppSettings
    {
        [JsonPropertyName("Number.Of.Retries")]
        public int NumberOfRetries { get; set; }
        public string Option1 { get; set; }
        public string Option2 { get; set; }
    }
}
    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.AddControllers();

        services.AddOptions();

        services.Configure<AppSettings>(Configuration); // This maps every key that matches existing property name

        services.PostConfigure<AppSettings>(appSettings =>// This maps keys where names don't match existing property names
        {
            appSettings.NumberOfRetries = Configuration.GetValue<int>("Number.Of.Retries");
        }); 
    }
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。使用此方法向容器中添加服务。
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
services.AddOptions();
services.Configure(Configuration);//映射与现有属性名匹配的每个键
services.PostConfigure(appSettings=>//此映射名称与现有属性名称不匹配的键
{
appSettings.NumberOfRetries=Configuration.GetValue(“重试次数”)