net6 webapi engineering development tool class

Instantiate the object into a json file

  1. Download JSON .Net from NuGet, install it into the required project, and install other packages
  2. Create a file
// 获取当前程序所在路径,并将要创建的文件命名为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. Serialized objects are stored in json files
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
File.WriteAllText(fp, JsonConvert.SerializeObject(obj));
  1. Read object information from the file (deserialization is enough)
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
Object obji = JsonConvert.DeserializeObject<Object>(File.ReadAllText(fp));  // 尖括号<>中填入对象的类名 

Three ways to get the directory where the application is located

  1. The first
string basePath1 = AppContext.BaseDirectory;
// D:\后端项目\testCore\test.WebApi\bin\Debug\net6.0\
  1. the second
string basePath2 =Path.GetDirectoryName(typeof(Program).Assembly.Location);
// D:\后端项目\testCore\test.WebApi\bin\Debug\net6.0\
  1. The third method: starting from ASP.NET Core RC2, you can obtain the physical path of the web root directory and the content root directory through dependency injection of the IHostingEnvironment service object
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.WebApi

            return Content(webRootPath + "\n" + contentRootPath);
        }
    }
}

Read appsettings configuration file

  1. First, create the ConfigHelper class
namespace TestProject.services
{
    public class ConfigHelper
    {
        private static IConfiguration _config;
 
        public ConfigHelper(IConfiguration configuration)
        {
            _config = configuration;
        }
 
        /// <summary>
        /// 读取appsettings.json文件中指定节点信息
        /// </summary>
        /// <param name="sessions"></param>
        /// <returns></returns>
        public static string ReadAppSettings(params string[] sessions)
        {
            try
            {
                if (sessions.Any())
                {
                    return _config[string.Join(":",sessions)];
                }
            }
            catch
            {
                return "";
            }
            return "";
        }
 
        /// <summary>
        /// 读取实体信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <returns></returns>
        public static List<T> ReadAppSettings<T>(params string[] session)
        {
            List<T> list = new List<T>();
            _config.Bind(string.Join(":",session),list);
            return list;
        }
    }
}
  1. Then add the following code in Program.cs to inject the service
var builder = WebApplication.CreateBuilder(args);

IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

builder.Services.AddSingleton(new ConfigHelper(configuration));
  1. Add the following code in appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Test": {
    "testStr1": "testvalue1",
    "testStr2": "testvalue2"
  },
}

  1. Finally, profile data can be read anywhere in the project
string str = ConfigHelper.ReadAppSettings("Test", "testStr1");
  1. Get the value of str as testvalue1

Guess you like

Origin blog.csdn.net/baidu_38493460/article/details/129527870