如果您想了解AppSetting配置工具类的相关知识,那么本文是一篇不可错过的文章,我们将对app进行配置进行全面详尽的解释,并且为您提供关于.netcore3.1ConsoleApp找不到配置文件'
如果您想了解AppSetting配置工具类的相关知识,那么本文是一篇不可错过的文章,我们将对app进行配置进行全面详尽的解释,并且为您提供关于.net core 3.1 Console App找不到配置文件'appsettings.json'、.net core appsettings 配置 serilog、.net core 中如何读取 appsettings.json 相关配置、.net core 中如何运用 appsettings.json 进行配置开发、生产不同配置的有价值的信息。
本文目录一览:- AppSetting配置工具类(app进行配置)
- .net core 3.1 Console App找不到配置文件'appsettings.json'
- .net core appsettings 配置 serilog
- .net core 中如何读取 appsettings.json 相关配置
- .net core 中如何运用 appsettings.json 进行配置开发、生产不同配置
AppSetting配置工具类(app进行配置)
1 <?xml version="1.0" encoding="utf-8"?> 2 <!-- 3 有关如何配置 ASP.NET 应用程序的详细信息,请访问 4 http://go.microsoft.com/fwlink/?LinkId=169433 5 --> 6 <configuration> 7 <appSettings> 8 <add key="key1" value="value1"/> 9 </appSettings> 10 </configuration>
一、缓存类
1 using System; 2 using System.Collections; 3 using System.Configuration; 4 using System.Web; 5 using System.Web.Caching; 6 7 namespace Common 8 { 9 /// <summary> 10 /// 缓存帮助类 11 /// author:陈彦斌 12 /// 时间:2019年7月14日14:25:30 13 /// httpruntime.cache 14 /// </summary> 15 public sealed class CacheHelper 16 { 17 /// <summary> 18 /// 获取configuratio节点下appSettings中add的值 19 /// </summary> 20 /// <param name="key">AppSettings的键</param> 21 /// <returns></returns> 22 public static object GetAppSttings(string key) 23 { 24 return ConfigurationManager.AppSettings[key]; 25 } 26 /// <summary> 27 /// 获取当前应用程序指定CacheKey的值 28 /// </summary> 29 /// <param name="CacheKey">appSettings节点下add中的键</param> 30 /// <returns></returns> 31 public static object GetCache(string CacheKey) 32 { 33 Cache objcache = httpruntime.cache; 34 return objcache[CacheKey]; 35 } 36 /// <summary> 37 /// 设置数据缓存(慎用) 38 /// </summary> 39 /// <param name="CacheKey">键</param> 40 /// <param name="CacheValue">值</param> 41 public static void SetCache(string CacheKey,object CacheValue) 42 { 43 Cache objcache = httpruntime.cache; 44 objcache.Insert(CacheKey,CacheValue); 45 } 46 /// <summary> 47 /// 设置数据缓存 48 /// </summary> 49 /// <param name="CacheKey">键</param> 50 /// <param name="CacheValue">值</param> 51 /// <param name="TimeOut">时间间隔</param> 52 public static void SetCache(string CacheKey,object CacheValue,TimeSpan TimeOut) 53 { 54 Cache objcache = httpruntime.cache; 55 objcache.Insert(CacheKey,CacheValue,null,DateTime.MaxValue,TimeOut,CacheItemPriority.NotRemovable,null); 56 } 57 /// <summary> 58 /// 设置数据缓存 59 /// </summary> 60 /// <param name="CacheKey">键</param> 61 /// <param name="CacheValue">值</param> 62 /// <param name="absoluteExpiration">绝对过期时间</param> 63 /// <param name="slidingExpiration">时间间隔</param> 64 public static void SetCache(string CacheKey,DateTime absoluteExpiration,TimeSpan slidingExpiration) 65 { 66 Cache objcache = httpruntime.cache; 67 objcache.Insert(CacheKey,null,absoluteExpiration,slidingExpiration); 68 } 69 /// <summary> 70 /// 移除全部缓存 71 /// </summary> 72 public static void RemovaAllCache() 73 { 74 Cache objcache = httpruntime.cache; 75 IDictionaryEnumerator CacheEnum = objcache.GetEnumerator(); 76 while (CacheEnum.MoveNext()) 77 { 78 objcache.Remove(CacheEnum.Key.ToString()); 79 } 80 } 81 /// <summary> 82 /// 移除指定键的缓存 83 /// </summary> 84 /// <param name="CacheKey">键</param> 85 public static void RemovaAllCache(string CacheKey) 86 { 87 Cache objcache = httpruntime.cache; 88 objcache.Remove(CacheKey); 89 } 90 } 91 }
二、AppSetting配置类
1 using System; 2 3 namespace Common 4 { 5 /// <summary> 6 /// web.config操作类 7 /// 使用前需引用程序集:System.configuration 8 /// </summary> 9 public sealed class ConfigHelper 10 { 11 /// <summary> 12 /// 获取AppSettings中配置String信息 13 /// </summary> 14 /// <param name="key">键</param> 15 /// <returns></returns> 16 public static string GetConfigString(string key) 17 { 18 object objValue = CacheHelper.GetCache(key); 19 if (objValue == null) //缓冲区没有值 20 { 21 objValue = CacheHelper.GetAppSttings(key); 22 if (objValue != null) 23 { 24 CacheHelper.SetCache(key,objValue,DateTime.Now.AddMinutes(180),TimeSpan.Zero); 25 } 26 } 27 return objValue.ToString(); 28 } 29 /// <summary> 30 /// 获取AppSettings中配置Bool信息 31 /// </summary> 32 /// <param name="key">键</param> 33 /// <returns></returns> 34 public static bool GetConfigBool(string key) 35 { 36 object objValue= CacheHelper.GetAppSttings(key); 37 if (StringUtil.isNullOrBlank(objValue)) 38 { 39 try 40 { 41 bool.Parse(objValue.ToString()); 42 return true; 43 } 44 catch 45 { 46 return false; 47 } 48 } 49 return false; 50 } 51 /// <summary> 52 /// 获取AppSettings中配置decimal信息 53 /// </summary> 54 /// <param name="key"></param> 55 /// <returns></returns> 56 public static decimal GetConfigDecimal(string key) 57 { 58 object objValue = CacheHelper.GetAppSttings(key); 59 if (StringUtil.isNullOrBlank(objValue)) 60 { 61 try 62 { 63 return decimal.Parse(objValue.ToString()); 64 } 65 catch 66 { 67 return 0; 68 } 69 } 70 return 0; 71 } 72 /// <summary> 73 /// 获取AppSettings中配置DateTime信息,可空 74 /// </summary> 75 /// <param name="key">键</param> 76 /// <returns></returns> 77 public static DateTime? GetConfigDateTime(string key) 78 { 79 DateTime? DateTimeNull = null; 80 object objValue = CacheHelper.GetAppSttings(key); 81 if (StringUtil.isNullOrBlank(objValue)) 82 { 83 try 84 { 85 return DateTime.Parse(objValue.ToString()); 86 } 87 catch 88 { 89 return DateTimeNull; 90 } 91 } 92 return DateTimeNull; 93 } 94 } 95 }
.net core 3.1 Console App找不到配置文件'appsettings.json'
如何解决.net core 3.1 Console App找不到配置文件''appsettings.json''?
在本地环境之外运行控制台应用程序时,.net core 3.1在与程序执行位置不同的目录中查找appsettings.json文件。
- 找不到配置文件''appsettings.json'',它不是可选的。物理路径为“ C:\ windows \ system32 \ appsettings.json”。
在早期版本的dotnet中,使用Environment.CurrentDirectory或Directory.GetCurrentDirectory(),但在3.1中不起作用。您如何更改它以使其在运行目录中显示?以下不起作用
using var host = Host.CreateDefaultBuilder()
.ConfigureHostConfiguration(builder =>
{
builder.SetBasePath(Environment.CurrentDirectory);
builder.AddCommandLine(args);
})
.UseConsoleLifetime(options => options.SuppressstatusMessages = true)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureAppConfiguration((hostContext,builder) =>
{
builder.AddJsonFile("appsettings.json");
hostContext.HostingEnvironment.EnvironmentName = Environment.GetEnvironmentvariable("NETCORE_ENVIRONMENT");
if (hostContext.HostingEnvironment.EnvironmentName == Environments.Development)
{
builder.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json",optional: true);
builder.AddUserSecrets<Program>();
}
})
解决方法
这似乎可以通过在设置基本路径之前从AppDomain.CurrentDomain获取基本目录来实现。我仍然不明白为什么以前的dotnet版本中不需要这样做,而且我也找不到与此有关的任何MS文档。
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
using var host = Host.CreateDefaultBuilder()
.ConfigureHostConfiguration(builder =>
{
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddCommandLine(args);
})
,
我们添加这样的应用设置:
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json",optional: false,reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional: true)
.AddEnvironmentVariables();
...
}
.net core appsettings 配置 serilog

"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Fatal",
"System": "Fatal"
}
},
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"pathFormat": "logs/{Date}.log",
"outputTemplate": "{Timestamp:HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"shared": true,
"restrictedToMinimumLevel": "Debug"
}
},
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "server=.;database=Qujiang_201905301637;uid=qujiang1;pwd=qujiang1;",
"tableName": "SeriLogs",
"autoCreateSqlTable": true,
"restrictedToMinimumLevel": "Warning",
"batchPostingLimit": 1000,
"columnOptionsSection": {
//"disableTriggers": true,
//"clusteredColumnstoreIndex": false,
//"primaryKeyColumnName": "Id",
//"addStandardColumns": [ "LogEvent" ],
"removeStandardColumns": [ "MessageTemplate", "Properties" ],
//"additionalColumns": [
// {
// "ColumnName": "EventType",
// "DataType": "int",
// "AllowNull": false
// },
// {
// "ColumnName": "Release",
// "DataType": "varchar",
// "DataLength": 32
// },
// {
// "ColumnName": "All_SqlColumn_Defaults",
// "DataType": "varchar",
// "AllowNull": true,
// "DataLength": -1,
// "NonClusteredIndex": false
// }
//],
"id": { "nonClusteredIndex": true },
"level": {
"columnName": "Severity",
"storeAsEnum": false
},
//"properties": {
// "columnName": "Properties",
// "excludeAdditionalProperties": true,
// "dictionaryElementName": "dict",
// "itemElementName": "item",
// "omitDictionaryContainerElement": false,
// "omitSequenceContainerElement": false,
// "omitStructureContainerElement": false,
// "omitElementIfEmpty": true,
// "propertyElementName": "prop",
// "rootElementName": "root",
// "sequenceElementName": "seq",
// "structureElementName": "struct",
// "usePropertyKeyAsElementName": false
//},
//"timeStamp": {
// "columnName": "Timestamp",
// "convertToUtc": true
//},
//"logEvent": {
// "excludeAdditionalProperties": true,
// "excludeStandardColumns": true
//},
"message": { "columnName": "Msg" },
"exception": { "columnName": "Ex" },
"messageTemplate": { "columnName": "Template" }
}
}
}
]
}
.net core 中如何读取 appsettings.json 相关配置
appsettings.json如下
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
"AllowedHosts": "*"
},
"ConfigSetting": {
"Ctu": 1,
"Btu": "Btu",
"Atu": "Atu"
}
}
建立实体ConfigSetting
public class ConfigSetting
{
public int Ctu { get; set; }
public string Btu { get; set; }
public string Atu { get; set; }
}
Startup配置
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.Configure<ConfigSetting>(Configuration.GetSection("ConfigSetting"));
}
Controller配置
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IOptions<ConfigSetting> _ConfigSettingt;
public ValuesController(IOptions<ConfigSetting> ConfigSetting)
{
_ConfigSettingt = ConfigSetting;
}
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return _ConfigSettingt.Value.Atu;
}
}
.net core 中如何运用 appsettings.json 进行配置开发、生产不同配置
.net core 默认会有 appsettings.Development.json 文件,这是根据ASPNETCORE_ENVIRONMENT来读取的。
新建架构appsettings.Production.json用于生成环境
开发调试时通过此处进行配置。
正式环境发布
IIS版本 - - - 通过生成的 web.config 进行配置 ASPNETCORE_ENVIRONMENT 环境变量
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\TTTTTTTTT.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" /><!--Development-->
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
后续更新。。。。
今天的关于AppSetting配置工具类和app进行配置的分享已经结束,谢谢您的关注,如果想了解更多关于.net core 3.1 Console App找不到配置文件'appsettings.json'、.net core appsettings 配置 serilog、.net core 中如何读取 appsettings.json 相关配置、.net core 中如何运用 appsettings.json 进行配置开发、生产不同配置的相关知识,请在本站进行查询。
本文标签: