WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
随笔 - 1079, 文章 - 1, 评论 - 75, 阅读 - 174万
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

.net core —— 控制台如何获取配置文件的内容?

Posted on   WebEnh  阅读(2899)  评论(0编辑  收藏  举报

本文链接:https://blog.csdn.net/yenange/article/details/82457761
参考: https://github.com/liuzhenyulive/JsonReader

在  Web 应用程序中, 获取配置文件还是比较简单的, 可以参考: 

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1#json-configuration-provider

但在控制台和类库中如何处理呢?

为了与 Web 保持一致, 配置文件名称还是使用:

appsettings.json

{
"ServerCode": "99",
"section0": {
"UserId": "1",
"UserName": "Tome"
},
"section1": {
"UserId": "2",
"UserName": "Marry"
}
}
下面展示了直接取字符串、绑定到实体及取子节点的几种方式:

using Microsoft.Extensions.Configuration;
using System;

namespace ConsoleApp4
{
class Program
{
//安装 .net core 2.1 完整包
//install-package Microsoft.AspNetCore.All -version 2.1.0
//注意不要超过 依赖项->SDK->Microsoft.NETCore.App 的版本,我这里是 2.1.0
//否则会无法正常生成和运行
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
Console.WriteLine("ServerCode:configuration["ServerCode"]");UserInfouser1=newUserInfo();UserInfouser2=newUserInfo();configuration.GetSection("section0").Bind(user1);configuration.GetSection("section1").Bind(user2);Console.WriteLine(user1.ToString());Console.WriteLine(user2.ToString());Console.WriteLine("section0:UserId:{configuration["section0:UserId"]}");
Console.Read();
}
}

public class UserInfo
{
public long UserId { get; set; }
public string UserName { get; set; }

public override string ToString()
{
return string.Format($"UserId:{UserId}, UserName:{UserName}");
}
}
}


还有一个问题: UserName 后面的值, 如果换成中文, 会显示乱码, 这个如何解决?

经 lindexi_gd 兄指点, 用 notepad++ 打开 json 文件, 改成 utf-8 编码, 就可以读取中文了, 表示感谢!

 


————————————————
版权声明:本文为CSDN博主「吉普赛的歌」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yenange/article/details/82457761

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多