[英].net core not able to read object out of appsettings.json
我的 dotnetcore 應用程序在從 appsettings.json 中讀取此 object 時出現問題:
"image": {
"ImagePresets": {
"SearchListing" : {"Width": 415, "Height": 220, "Fit": true},
"PropertyPage" : {"Width": 650, "Height": 350, "Fit": true},
"Large" : {"Width": 910, "Height": 650, "Fit": true},
"FeaturedLocation" : {"Width": 272, "Height": 296, "Fit": true}
}
},
這是 object 我試圖將其反序列化為:
public class ImagePresets
{
public Preset SearchListing { get; set; }
public Preset PropertyPage { get; set; }
public Preset Large { get; set; }
public Preset FeaturedLocation { get; set; }
public ImagePresets()
{
FeaturedLocation = SearchListing = Large = PropertyPage = new Preset();
}
}
public class Preset
{
int Width { get; set; }
int Height { get; set; }
bool Fit { get; set; }
}
這就是我試圖閱讀它的方式:
ImagePresets _presets = _config.GetSection("image:ImagePresets").Get<ImagePresets>();
當我嘗試執行_config.GetSection("image:ImagePresets").GetChildren()
我確實得到了 KeyValuePairs,但反序列化總是返回空值,例如:
Fit [bool]:
false
Height [int]:
0
Width [int]:
0
我究竟做錯了什么? 任何幫助,將不勝感激。
這僅僅是因為Preset
的屬性是不公開的。 這有效
public class Preset
{
public int Width { get; set; }
public int Height { get; set; }
public bool Fit { get; set; }
}
根據文檔:
一個選項 class:
- 必須是非抽象的,具有公共無參數構造函數。
- 該類型的所有公共讀寫屬性均已綁定。
El problema es que las propiedades de la clase Presset con privadas, deberían ser publicas para que puedan ser accesibles。
public class Preset
{
public int Width { get; set; }
public int Height { get; set; }
public bool Fit { get; set; }
}
如果我沒記錯的話,你會得到如下代碼的值:
public class ClassName{
public ClassName(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
YourClass YourMethod() {
return Configuration["image:ImagePresets:SearchListing"];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.