在现代C#开发中,尤其是使用.NET Core或.NET 5+构建应用程序时,配置文件读取是每个开发者必须掌握的基础技能。本文将围绕appsettings.json这一核心配置文件,从零开始教你如何在C#项目中正确读取和使用配置信息,即使你是编程小白也能轻松上手!
appsettings.json 是 .NET Core 及更高版本中默认的配置文件,采用 JSON 格式存储应用程序的设置,如数据库连接字符串、API密钥、日志级别等。它替代了传统 .NET Framework 中的 web.config 或 app.config 文件,更加轻量、灵活且跨平台。
在你的 C# 项目根目录下(通常与 Program.cs 同级),你会看到一个名为 appsettings.json 的文件。如果没有,请手动创建。
以下是一个典型的配置示例:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "AppSettings": { "Title": "我的C#应用", "Version": "1.0.0", "MaxRetryCount": 3 }, "ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=MyAppDb;Trusted_Connection=true;" }} 在 .NET 6 及以上版本中,项目使用了简化主机模型。你无需手动添加配置服务,因为框架已自动加载 appsettings.json。但为了确保一切正常,我们来看看标准做法:
var builder = WebApplication.CreateBuilder(args);// 此时 appsettings.json 已被自动加载到 IConfiguration// 你可以通过 builder.Configuration 访问配置var app = builder.Build();app.MapGet("/", () => "Hello World!");app.Run(); 有多种方式可以读取 appsettings.json 中的配置。下面介绍两种最常用的方法。
// 在控制器或服务中注入 IConfigurationpublic class HomeController : Controller{ private readonly IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; } public IActionResult Index() { // 读取简单字符串 string title = _configuration["AppSettings:Title"]; // 读取整数(需转换) int maxRetry = int.Parse(_configuration["AppSettings:MaxRetryCount"]!); // 读取连接字符串 string connStr = _configuration.GetConnectionString("DefaultConnection"); ViewBag.Title = title; return View(); }} 这种方式更安全、更易维护。
首先,定义一个类来匹配 JSON 结构:
public class AppSettings{ public string Title { get; set; } = string.Empty; public string Version { get; set; } = string.Empty; public int MaxRetryCount { get; set; }} 然后在 Program.cs 中注册该配置:
// Program.csvar builder = WebApplication.CreateBuilder(args);// 将 AppSettings 部分绑定到 AppSettings 类builder.Services.Configure( builder.Configuration.GetSection("AppSettings"));var app = builder.Build();app.Run();
最后,在需要的地方注入并使用:
public class SomeService{ private readonly AppSettings _appSettings; public SomeService(IOptions options) { _appSettings = options.Value; } public void DoWork() { Console.WriteLine($"应用名称: {_appSettings.Title}"); Console.WriteLine($"最大重试次数: {_appSettings.MaxRetryCount}"); }} appsettings.Development.json、appsettings.Production.json 等文件,框架会自动按环境加载。通过本教程,你已经掌握了在 C# 项目中如何使用 appsettings.json 进行配置文件读取。无论是简单的键值对还是复杂的嵌套对象,.NET 的配置系统都能优雅地处理。记住,良好的配置管理是构建可维护、可部署应用的关键一步。
关键词回顾:C#配置文件读取、appsettings.json教程、.NET Core配置管理、C#读取JSON配置。
本文由主机测评网于2025-12-07发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025124179.html