net6 webapi エンジニアリング開発ツール クラス

オブジェクトを 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<Object>(File.ReadAllText(fp));  // 尖括号<>中填入对象的类名 

アプリケーションが置かれているディレクトリを取得する 3 つの方法

  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. 3 番目の方法: 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.WebApi

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

アプリ設定構成ファイルを読み取る

  1. まず、ConfigHelper クラスを作成します。
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. 次に、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 として取得します

おすすめ

転載: blog.csdn.net/baidu_38493460/article/details/129527870