.net - 从 .Net Core 2.0 Web 应用程序中的 apppsettings.json 文件中读取值
问题描述
我正在.Net Core 2.0 中启动一个小型开源项目,以了解这种技术。我有一个空项目,我需要从远程 URL 提要中读取 beginig。我需要那个,可以修改 URL,我认为最好的方法是将它写在项目的 appsettings.json 文件中。但我不知道如何从 Startup.cs 类中读取此文件。
我已经尝试过了,但在 .Net Core 项目中不起作用
ConfigurationManager.AppSettings["DataURL"];
这是 Startup.cs 类的内容:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
using (WebClient wc = new WebClient())
{
string jsonData = wc.DownloadString("http://servizos.meteogalicia.gal/rss/observacion/ultimos10minPlataformas.action");
JObject jsonObject = JObject.Parse(jsonData);
}
});
}
}
解决方案
使用依赖注入,您将为您完成 IConfiguration 对象。看到这个
public class Startup
{
private readonly IConfiguration _ConfigurationManager ;
public Startup(IConfiguration config)
{
_ConfigurationManager = config;
}
......
您现在可以使用读取 appsettings 值var DataURL =_ConfigurationManager ConfigurationManager["DataURL"];
推荐阅读
- algorithm - 如何有效地将大范围的索引值从 1 翻转到 0,反之亦然
- javascript - Material-UI 覆盖 .MuiDataGrid-columnsContainer CSS
- r - 处理 xts - R 中日期变化的计算
- javascript - 更多阅读 ngx-datatable-columns
- linux - FFmpeg Drawbox 错误?
- mysql - 错误代码:1054。尝试 JOIN 两个表时,“on 子句”中的未知列“diagnoses.PATIENT_IDENTIFIER”
- sql - 使用 SQL 计算排列
- java - io.reactivex.exceptions.UndeliverableException 异常无法交付给消费者,因为它已经取消/处置
- php - .htaccess 规则重定向到默认 API 版本
- tcp - channel.close() 是否真的通过 channel.eventLoop().scheduleAtFixedRate() 停止计划任务?