我正在编写自己的扩展方法ServiceCollection来注册模块的类型,我需要IConfiguration从集合中访问实例来注册我的选项.
扩展方法
public static IServiceCollection AddApi(this IServiceCollection services)
{
// Get configuration from collection
var configuration = (IConfiguration) services.FirstOrDefault(p => p.ServiceType == typeof(IConfiguration)).ImplementationInstance;
services.Configure<DatabaseOptions>(configuration.GetSection("Database"));
}
Run Code Online (Sandbox Code Playgroud)
这是IConfiguration从集合中获取实例的正确方法还是有更优雅的解决方案?我不想将IConfiguration实例作为参数添加到方法中.
ASP.NET Core是否实现了IConfiguration对配置值的访问?
很可能是我的问题出现了,因为我不明白ASP.NET核心到底是什么.好吧,我知道它是一个Web框架,不确定,但看起来它是.NET中的命名空间,或者一个包...我知道在php中,框架可以是一组类(命名空间)或编译库,作为扩展提供,所以我在.NET中假设一个类似的方法.
最初,我并不打算围绕ASP.NET Core.我需要为我的简单控制台C#应用程序(VS Code和.NET Core)存储一些配置.我发现了许多主题(例如这里:如何从控制台应用程序中的config.json读取值)来读取JSON(推荐)配置.鉴于此,我添加了三个必要的块包:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.FileExtensions;
using Microsoft.Extensions.Configuration.Json;
Run Code Online (Sandbox Code Playgroud)
我需要用:
new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
Run Code Online (Sandbox Code Playgroud)
这将返回实现IConfigurationRoot/ IConfigurationinterface 的对象.但是所有示例都是在ASP.NET Core上下文中给出的.我有一个非常简单的应用程序,我还不需要任何ASP.NET功能.
所以我试图在IConfigurationRoot没有ASP.NET的情况下访问.生成的对象存储来自配置文件的值,但没有其接口的所有方法来访问它们.
如何在.NET命名空间的上下文中解释这一点?ASP.NET Core是否实现了从IConfiguration类似访问值的方法Get<T>()?
如果Microsoft.Extensions.Configuration是一部分或严重依赖Microsoft.AspNetCore.App,为什么它在不同的命名空间?
如果我添加ASP.NET Core(NuGet包和命名空间),它会是一种矫枉过正吗?
也许我应该使用soemthing而不是ConfigurationBuilder阅读JSON?
在我的 Azure 中,我有ENVIRONMENT = Development,但我的设置未加载。
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) // reloadOnChange Whether the configuration should be reloaded if the file changes.
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ENVIRONMENT")}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables() // Environment Variables override all other, ** THIS SHOULD ALWAYS BE LAST
.Build();
Run Code Online (Sandbox Code Playgroud)
但它始终使用默认设置。
c# asp.net-core asp.net-core-webapi asp.net-core-configuration
我正在尝试从mac部署IIS上的asp.net核心2.0 api项目.
我想要做的是为我的开发,登台和生产环境设置不同的appsettings.json文件,然后使用dotnet -build作为我的部署脚本的一部分来调用不同的环境.
我看过https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments,这是针对旧版.net核心的,我无法理解我需要做的事情.我不是为操作系统设置环境,而是以编程方式设置它(因为我的登台和生产环境是针对同一台服务器的)
我有一个appsettings.Development.json文件,它在我运行我的应用程序时使用,但我似乎无法在设置环境变量作为构建命令的一部分时加载我的appsettings.Production.json文件.
bash$ ASPNETCORE_ENVIRONMENT=Production dotnet run
Using launch settings from /Properties/launchSettings.json...
Hosting environment: Development
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Run Code Online (Sandbox Code Playgroud)
最终,我正在尝试根据我构建的环境部署特定的连接字符串.有一个更好的方法吗?
更新
@Chris的回答有帮助,另外我发现了以下内容:
每个IIS应用程序池如果需要为在隔离的应用程序池中运行的各个应用程序设置环境变量(在IIS 10.0+上受支持),请参阅IIS参考文档中的环境变量主题的AppCmd.exe命令部分.
这让我可以为每个应用程序池设置不同的环境
我无法让我Configuration.GetSection返回.Value. 我想我实施了这个问题的所有建议,但仍然无法让它发挥作用。
appsettings.json
{
"AmazonSettings": {
"BaseUrl": "https://testing.com",
"ClientID": "123456",
"ResponseType": "code",
"RedirectUri": "https://localhost:44303/FirstTimeWelcome"
},
}
Run Code Online (Sandbox Code Playgroud)
启动:
public IConfiguration Configuration { get; }
public Startup(IHostingEnvironment env)
{
//Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
Run Code Online (Sandbox Code Playgroud)
配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AmazonSettings>(Configuration.GetSection("AmazonSettings"));
services.AddMvc()
Run Code Online (Sandbox Code Playgroud)
AmazonSettings 类:
public class AmazonSettings
{
public string BaseUrl { get; set; }
public string ClientID { get; set; …Run Code Online (Sandbox Code Playgroud) 我的 asp.net core (5) 应用程序中有以下内容:
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
并在appsettings.json下面的内容中
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"MyApp": "Information",
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithProcessId",
"WithThreadId"
],
"WriteTo": [
{
"Name": "Console",
"outputTemplate": "{Timestamp:G}[{Level:u3}] ** {Message} ** ({SourceContext}) {NewLine:1}{Exception:1}"
},
{
"Name": "File",
"Args": {
"path": "C:\\logs\\MyApp\\log.txt",
"outputTemplate": "{Timestamp:G}[{Level:u3}] ** {Message} *** ({SourceContext}) {NewLine:1}{Exception:1}"
}
},
{ …Run Code Online (Sandbox Code Playgroud) .net serilog asp.net-core asp.net-core-configuration asp.net-core-5.0
在我的.NET Core项目中,Configure方法中具有以下设置:
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//services.AddOptions<UploadConfig>(Configuration.GetSection("UploadConfig"));
}
Run Code Online (Sandbox Code Playgroud)
我还没有注册任何东西IOptions,我正在将其注入控制器中
[Route("api/[controller]")]
[ApiController]
public class HelloWorldController : ControllerBase
{
public HelloWorldController(IOptions<UploadConfig> config)
{
var config1 = config.Value.Config1;
}
}
Run Code Online (Sandbox Code Playgroud)
该IOptions是越来越有默认实例解析,和我只知道,当我尝试使用它(当我所期望的价值是不为空)错误。
我能否以某种方式使其失败,说明实例类型未注册或类似原因?我只想尽早发现错误。
c# dependency-injection .net-core asp.net-core asp.net-core-configuration
I am trying to load my app settings with ASP.NET Core Options pattern.
The appsettings.json contains:
{
"TEst": "hello",
"TEST_ABC": "2"
}
Run Code Online (Sandbox Code Playgroud)
POCO class:
public class AppSetting
{
public string Test { get; set; }
public string TestAbc { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Bind to configuration:
services.Configure<AppSetting>(Configuration);
Run Code Online (Sandbox Code Playgroud)
While access AppSetting instance in controller, I can only get config Test as hello. TestAbc is set to null.
It seems Options pattern couldn't convert this kind of naming configuration, is …
我有一个 .net core 3.1 Console 项目。我正在尝试将其设置为使用 NLog。我使用 2 个目标,数据库和文件。我可以写入文件,但不能写入数据库。我确信连接字符串是正确的,因为我在其他项目中使用它,但它们是在 4.7 框架中编写的。
这是我的 app.config 设置:
<connectionStrings>
<add name="NLog" connectionString="Data Source=mySource;Initial Catalog=MyLogging;Integrated Security=SSPI;" />
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)
这是我尝试在目标中设置它:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Info"
internalLogFile="c:\temp\nlog-internal.log">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<target name="database" xsi:type="Database" connectionString="${configsetting:name=NLog}" commandType="StoredProcedure" commandText="[dbo].[MyLogEntry]">
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="Database" />
</rules>
</nlog>
Run Code Online (Sandbox Code Playgroud)
来自 c:\temp\nlog-internal.log 的错误消息是:
2021-02-10 16:11:48.3381 Error DatabaseTarget(Name=database): Error when writing to …Run Code Online (Sandbox Code Playgroud) connection-string app-config nlog asp.net-core-configuration asp.net-core-3.1
我有一个非常简单的方法,需要对它进行单元测试。
public static class ValidationExtensions
{
public static T GetValid<T>(this IConfiguration configuration)
{
var obj = configuration.Get<T>();
Validator.ValidateObject(obj, new ValidationContext(obj), true);
return obj;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是这configuration.Get<T>是静态扩展方法,不属于IConfiguration。我无法更改该静态方法的实现。
我在想,也许最简单的方法是创建内存配置提供程序?但是我不知道是否可以在不将其绑定到Web主机的情况下创建一个。
在 ASP.NET Core 3.1 启动类和控制器之间共享配置对象的最佳方式是什么?
我看过一些使用 DI 的例子,这看起来是个好主意,但我需要在public void ConfigureServices(IServiceCollection services).
此外,对象依赖于一个Microsoft.Extensions.Configuration.IConfiguration实例。
该对象将在 内
Startup.cs、ConfigureServices自身内以及在 内使用Controllers。
DI 会工作吗?或者解决方案是带参数的单例?
下面是需要分享的具体代码:
// openssl rand -hex 16 => 256 bits when read
var jwt_key = Configuration.GetSection("JwtOption:IssuerSigningKey").Value;
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwt_key));
var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = "some host name", …Run Code Online (Sandbox Code Playgroud) asp.net-core-configuration ×11
asp.net-core ×9
c# ×8
.net-core ×2
.net ×1
app-config ×1
nlog ×1
serilog ×1
unit-testing ×1