首页 > 解决方案 > 从 .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);
            }

        });
    }
}

标签: .netasp.net-core

解决方案


使用依赖注入,您将为您完成 IConfiguration 对象。看到这个

public class Startup
{
    private readonly IConfiguration _ConfigurationManager ;

    public Startup(IConfiguration config)
    {
        _ConfigurationManager = config;
    }
......

您现在可以使用读取 appsettings 值var DataURL =_ConfigurationManager ConfigurationManager["DataURL"];


推荐阅读