net6 webapi工程开发工具类
创始人
2024-06-03 09:43:04
0

文章目录

      • 将对象实例化成json文件
      • 获取应用程序所在目录的三种方式
      • 读取appsettings配置文件

将对象实例化成json文件

  1. 从NuGet上下载JSON .Net,安装到所需项目中,安装其它包也可以
  2. 创建文件
// 获取当前程序所在路径,并将要创建的文件命名为info.json 
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
if (!File.Exists(fp))  // 判断是否已有相同文件
{FileStream fs1 = new FileStream(fp, FileMode.Create, FileAccess.ReadWrite);  fs1.Close();
}
  1. 序列化对象存储到json文件中
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
File.WriteAllText(fp, JsonConvert.SerializeObject(obj));
  1. 从文件中读取对象信息(反序列化即可)
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
Object obji = JsonConvert.DeserializeObject(File.ReadAllText(fp));  // 尖括号<>中填入对象的类名 
 

获取应用程序所在目录的三种方式

  1. 第一种
string basePath1 = AppContext.BaseDirectory;
// D:\后端项目\testCore\test.WebApi\bin\Debug\net6.0\
  1. 第二种
string basePath2 =Path.GetDirectoryName(typeof(Program).Assembly.Location);
// D:\后端项目\testCore\test.WebApi\bin\Debug\net6.0\
  1. 第三种:从ASP.NET Core RC2开始,可以通过依赖注入 IHostingEnvironment 服务对象来取得Web根目录和内容根目录的物理路径
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;namespace AspNetCorePathMapping
{public class HomeController : Controller{private readonly IHostingEnvironment _hostingEnvironment;public HomeController(IHostingEnvironment hostingEnvironment){_hostingEnvironment = hostingEnvironment;}public ActionResult Index(){string webRootPath = _hostingEnvironment.WebRootPath;string contentRootPath = _hostingEnvironment.ContentRootPath;// webRootPath: D:\后端项目\testCore\test.WebApi\wwwroot// contentRootPath: D:\后端项目\testCore\test.WebApireturn Content(webRootPath + "\n" + contentRootPath);}}
}

读取appsettings配置文件

  1. 首先,创建 ConfigHelper类
namespace TestProject.services
{public class ConfigHelper{private static IConfiguration _config;public ConfigHelper(IConfiguration configuration){_config = configuration;}/// /// 读取appsettings.json文件中指定节点信息/// /// /// public static string ReadAppSettings(params string[] sessions){try{if (sessions.Any()){return _config[string.Join(":",sessions)];}}catch{return "";}return "";}/// /// 读取实体信息/// /// /// /// public static List ReadAppSettings(params string[] session){List list = new List();_config.Bind(string.Join(":",session),list);return list;}}
}
  1. 然后在Program.cs中添加如下代码注入服务
var builder = WebApplication.CreateBuilder(args);IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();builder.Services.AddSingleton(new ConfigHelper(configuration));
  1. 在 appsettings.json中添加如下代码
{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*","Test": {"testStr1": "testvalue1","testStr2": "testvalue2"},
}
  1. 最后,可以在项目的任意地方读取配置文件数据
string str = ConfigHelper.ReadAppSettings("Test", "testStr1");
  1. 得到 str 的值为 testvalue1

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...