相关疑难解决方法(0)

ASP.NET Core 6+ 如何在启动过程中访问配置

在早期版本中,我们有 Startup.cs 类,并在Startup文件中获取配置对象,如下所示。

public class Startup 
{
    private readonly IHostEnvironment environment;
    private readonly IConfiguration config;

    public Startup(IConfiguration configuration, IHostEnvironment environment) 
    {
        this.config = configuration;
        this.environment = environment;
    }

    public void ConfigureServices(IServiceCollection services) 
    {
        // Add Services
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
    {
        // Add Middlewares
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,在 .NET 6 及更高版本(使用 Visual Studio 2022)中,我们看不到Startup.cs类。看来它的日子屈指可数了。那么我们如何获取配置(IConfiguration)和托管环境(IHostEnvironment)等对象

我们如何获取这些对象,也就是说从 appsettings 读取配置?目前,Program.cs 文件如下所示。

using Festify.Database;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<FestifyContext>();


//////////////////////////////////////////////// …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core .net-6.0 .net-7.0

255
推荐指数
7
解决办法
25万
查看次数

ASP.NET 5(vNext) - 获取配置设置

我正在编写一个基本的应用程序来学习ASP.NET 5.我觉得困惑的一个领域是配置.在ASP.NET 5之前,我可以执行以下操作:

var settingValue = ConfigurationManager.AppSettings["SomeKey"];
Run Code Online (Sandbox Code Playgroud)

我会在我的代码中散布各种代码.现在,在vNext世界中,我有一个如下所示的config.json文件:

config.json

{
  "AppSettings": {
    "SomeKey":"SomeValue"
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在Startup.cs中,我有以下内容: Startup.cs

public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment) 
{
  Configuration = new Configuration()
      .AddJsonFile("config.json");
}
Run Code Online (Sandbox Code Playgroud)

从那里,我完全难过.我在/src/Website/Code/Models/MyClass.cs中有MyClass.cs.

MyClass.cs

public class MyClass
{
  public string DoSomething() 
  {
    var result = string.Empty;
    var keyValue = string.Empty; // TODO: What do I do here? How do I get the value of "AppSettings:SomeKey"?
    return result;
  }
}
Run Code Online (Sandbox Code Playgroud)

如何获得"AppSettings:SomeKey"的值?

.net c# asp.net .net-core asp.net-core

42
推荐指数
4
解决办法
3万
查看次数

如何从appsettings.json获取价值

public class Bar
{
    public static readonly string Foo = ConfigurationManager.AppSettings["Foo"];
}
Run Code Online (Sandbox Code Playgroud)

在.NET Framework 4.x的,我可以用ConfigurationManager.AppSettings ["Foo"]得到FooWebconfig,然后我可以轻松地获得的值Foo通过Bar.Foo

但是在.Net核心中,我必须注入options,并且无法获得Foo通过的价值Bar.Foo

有没有一种方法,可以直接通过Bar.Foo获取值来获得 Foo

.net appsettings

41
推荐指数
4
解决办法
5万
查看次数

访问控制器类中的appsettings.json值

无法弄清楚如何读取startup.cs之外的appsettings.json值.我想做的是,例如,在_Layout.cshtml中,从配置中添加站点名称:

例如:

ViewData["SiteName"] = Configuration.GetValue<string>("SiteSettings:SiteName");
Run Code Online (Sandbox Code Playgroud)

甚至更好:

public class GlobalVars {
    public static string SiteName => Configuration.GetValue<string>("SiteSettings:SiteName");
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我的代码:

[appsettings.json]

"SiteSettings": {
    "SiteName": "MySiteName"
}
Run Code Online (Sandbox Code Playgroud)

[startup.cs]

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();

    var siteName = Configuration.GetValue<string>("SiteSettings:SiteName");
}

public IConfigurationRoot Configuration { get; }
Run Code Online (Sandbox Code Playgroud)

也许我正在阅读文档错误,但我似乎无法在Startup类之外公开Configuration对象.

c# appsettings asp.net-core-mvc

13
推荐指数
1
解决办法
1万
查看次数

获取所有设置的Asp.Net Core 2.0中的Configuration.GetSection

我正在尝试学习检索配置信息的各种方法,以便我可以确定为即将开始的项目设置和使用配置的最佳途径.

我可以使用访问各种单一设置

var sm = new SmsSettings
    {
        FromPhone = Configuration.GetValue<string>("SmsSettings:FromPhone"),               
        StartMessagePart = Configuration.GetValue<string>("SmsSettings:StartMessagePart"),               
        EndMessagePart = Configuration.GetValue<string>("SmsSettings:EndMessagePart")
    };
Run Code Online (Sandbox Code Playgroud)

我还需要能够计算设置,确定某些设置的值等.所以我正在构建一个解析方法来执行这些类型的事情,并且需要设置文件的整个部分,这就是我假设的GetSection所做的.错误.

appsettings文件

{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo;Trusted_Connection=True;MultipleActiveResultSets=true",
  "ProductionConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Production;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Warning"
  }
},   
"SmsSettings": {
  "FromPhone": "9145670987",      
  "StartMessagePart": "Dear user, You have requested info from us on starting",      
  "EndMessagePart": "Thank you."
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是两个截图

var section = Configuration.GetSection("ConnectionStrings");
Run Code Online (Sandbox Code Playgroud)

回报

图1:变量属性

图2:深入研究JsonConfigurationProvider

出现了一些问题.

  1. 为什么这会返回3个不同的JsonConfigurationProviders,其中一个包含appsettings.json文件中的每个设置(如图2所示)
  2. 为什么GetSection("ConnectionStrings")不能实现这一点,返回ConnectionStrings的子子元素
  3. 给定数字2,你如何实际检索ConnectionStrings的子项?
  4. 假设模型ConnectionStrings具有一个属性List Connections,该部分可以转换为对象吗?

configuration asp.net-core-2.0

10
推荐指数
4
解决办法
3万
查看次数

Asp.Net核心如何更换配置管理器

我是ASP.NET Core RC2的新手,我想知道如何获得一些配置设置并将其应用到我的方法中.对于我的实例appsettings.json我有这个特定的设置

"ConnectionStrings": {
    "DefaultConnection": 
        "Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"
  }
Run Code Online (Sandbox Code Playgroud)

在我的Controller中,每次我想查询数据库时,我都必须使用此设置

 using (var conn = 
     new NpgsqlConnection(
         "Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"))
 {
     conn.Open();
 }
Run Code Online (Sandbox Code Playgroud)

这里显而易见的是,如果我想在配置中添加更多内容,我必须更改该方法的每个实例.我的问题是如何才能进入DefaultConnection,appsettings.json这样我才能做到这一点

 using (var conn = 
     new NpgsqlConnection(
         ConfigurationManager["DefaultConnection"))
 {
     conn.Open();
 }
Run Code Online (Sandbox Code Playgroud)

c# asp.net npgsql asp.net-core asp.net-core-1.0

6
推荐指数
2
解决办法
9124
查看次数

覆盖 azure 应用服务应用程序设置中的数组

在我的 .NET Core 应用程序中,我向 appsettings.json 添加了一个数组,如下所示:

{
  "SettingsA": {
    "PropA": [
        "ChildObjectA": {
          ...
        },
        "ChildObjectB": {
          ...
        }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我想从我的 azure 应用程序服务中的应用程序设置中覆盖该值,以便它具有空数组:

{
  "SettingsA": {
    "PropA": []
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

我试着把

SettingsA:PropsA  ->  []
Run Code Online (Sandbox Code Playgroud)

在应用程序设置中,但它似乎没有覆盖 appsettings.json 的值

c# azure azure-web-app-service asp.net-core

6
推荐指数
2
解决办法
4487
查看次数

如何使用 .NET Core 从控制台应用程序中的 appsettings.json 获取值?

我正在使用 .NET Core 3.1 创建一个控制台应用程序,我想要一个 appsettings json 在执行开始时加载所有环境、路径、变量...,然后从其他库类中获取值。我已经使用 appsettings json 中包含的数据创建了一个“设置”类。这是我在教程中已经看到的,但我无法获得任何价值。

//Start.cs
public class Startup
{
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
}

//Settings.cs
 public class Settings
    {
        public ConnectionStrings ConnectionStrings { get; set; }
        public Logging Logging { get; set; }
        public AppSettings AppSettings { get; set; } …
Run Code Online (Sandbox Code Playgroud)

c# startup appsettings .net-core

6
推荐指数
5
解决办法
1万
查看次数

如何在 ASP.NET Core 6 控制器中访问 appsettings.json 中的值

我根据 Visual Studio 2022 中提供的默认模板创建了一个全新的 ASP.NET Core Web API 项目 (.NET 6)。之后,我在 appsettings.json 文件中添加了一个配置密钥controller并尝试在类中访问它,但不能。

我的appsettings.json文件如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ProjectName" : "VeryFunny"
}

Run Code Online (Sandbox Code Playgroud)

控制器代码如下:

public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly IConfiguration _configuration;

    public WeatherForecastController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-webapi .net-6.0

6
推荐指数
2
解决办法
2万
查看次数

ConfigurationManager 是否与 ASP.NET core 的 appsettings.json 一起使用?

我有一个 .NET Standard 库,其中包含我所有的 SQL 相关代码。它甚至包含一些创建 SQL 连接的代码。该库需要从应用程序配置文件中读取以获取 SQL 连接字符串。图书馆正在使用典型的ConfigurationManager.ConnectionStrings方法。

现在,我在 .NET Core ASP.NET Web Api 2 应用程序中使用了这个库。我已经在这个应用程序的appsettings.json文件中定义了我的连接字符串。连接字符串位于ConnectionStrings具有给定名称的字段中,该名称与我上面的 DLL 查找的名称相匹配。

这似乎不起作用。我的 DLL 从顶部开始,没有从配置文件中找到连接字符串。

难道ConfigurationManager不是一起工作appsettings.json?如果没有,我应该如何解决这个问题?

c# asp.net .net-core

5
推荐指数
1
解决办法
6407
查看次数

读取appsettings.json-字段保持为空

认为我的startup.cs有问题,因为我没有从我那里得到任何值 <IOption> config

所以..我们有我们的appsettings.json

"Config": {
    "ApplicationName": "some name",
    "ConnectionString": "someconstring",
    "Version": "1.0.0"
  },
Run Code Online (Sandbox Code Playgroud)

在这里,我们有我们的模型

public class Config
    {   
        public string ApplicationName { get; set; }
        public string ConnectionString { get; set; }
        public string Version { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

startup.cs

 public Startup(IConfiguration configuration)

    {
        Configuration = configuration;
    }



public static IConfiguration Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection …
Run Code Online (Sandbox Code Playgroud)

c# asp.net json asp.net-core

4
推荐指数
1
解决办法
1864
查看次数

如何在标准类库中读取 .Net Core 配置?

今天(2016 年 11 月 11 日)我下载了新的 Visual Studio 2017 RC,安装了 .Net Core 1.1 并设置了一个 Web Api 项目(ASP.NET Core Web 应用程序(.NET Core))。然后我按照有关如何从配置文件读取应用程序设置的说明进行操作。这工作得很好。

然后我在同一个解决方案中创建了一个新项目。这是.NET Core部分下的类库 (.NET Standard)。我添加了一个带有接口的类,并使用默认的依赖注入进行了设置。

最后,我尝试通过构造函数注入使用类库中的配置。我收到此错误消息:

找不到类型或命名空间名称“IOptions<>”

这是我在类库中的类:

public class Firebase : IDatabase
{
    public Firebase(IOptions<AppSettings> appSettings)
    {
        //string basePath = 
    }
}  
Run Code Online (Sandbox Code Playgroud)

下面是 Startup.cs 中的 ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddTransient<IDatabase, Firebase>();

        // Set up configuration files.
        services.AddOptions();
        services.Configure<AppSettings>(options => Configuration.GetSection("AppSettings").Bind(options)); …
Run Code Online (Sandbox Code Playgroud)

.net-core asp.net-core-webapi

2
推荐指数
1
解决办法
3510
查看次数