我正试图从appsetings.json文件中读取一些数据:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
//sercies.Configure<Models.AppDate>(Configuration);
services.Configure<Models.AppData>(Configuration.GetSection("AppData"));
//It does not works
string option = Configuration.Get<Models.AppData>().AnotherOption;
//It works
string anotherOption = Configuration["AppData:AnotherOption"];
// Add framework services.
services.AddMvc();
}
使用这些课程:
public class AppData
{
public Jwt Jwt { get; set; }
public string AnotherOption { get; set; }
}
public class Jwt
{
public string Audience { get; set; }
public string Issuer { get; set; }
}
在appsettings.json中:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AppData": {
"Jwt": {
"Audience": "http://localhost:5000",
"Issuer": "http://localhost:5000"
},
"AnotherOption": "Not yet"
}
}
当我调试时,选项var it为null。 ¿我怎么能实现这个? TY
答案 0 :(得分:0)
我不确定为什么上面的代码不起作用。 但我知道其他方法。
string option = Configuration.GetSection("AppData").Get<Models.AppData>().AnotherOption;
或
string option = ConfigurationBinder.Get<Models.AppData>(Configuration.GetSection("AppData")).AnotherOption;
答案 1 :(得分:0)
public void ConfigureServices(IServiceCollection services)
{
var config = Configuration.GetSection("Application").Get<Application>();
}
//Model class
public class Application
{
public string ServiceUrl { get; set; }
}
下面的方法可以访问appsettings.json
中的数据namespace Particles
{
class ParticleGenerator
{
Texture2D texture;
float spawnWidth;
float density;
List<Particles> particles = new List<Particles>();
float timer;
public ParticleGenerator(Texture2D newTexture, float newSpawnWidth, float newDensity)
{
texture = newTexture;
spawnWidth = newSpawnWidth;
density = newDensity;
}
public void createParticle(GraphicsDevice graphics)
{
particles.Add(new Particles(texture, new Vector2(graphics.Viewport.Width / 2 , graphics.Viewport.Height /2), new Vector2(5, 1)));
}
public void Update(GameTime gameTime, GraphicsDevice graphics)
{
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
while (timer > 0)
{
timer -= 1f / density;
createParticle(graphics);
}
for (int i = 0; i < particles.Count; i++)
{
particles[i].Update();
if (particles[i].Position.Y > graphics.Viewport.Height)
{
particles.RemoveAt(i);
i--;
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (Particles particle in particles)
{
particle.Draw(spriteBatch);
}
}
}