学习Net Core 2.0 做博客 操作json文件读写

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习Net Core 2.0 做博客 操作json文件读写相关的知识,希望对你有一定的参考价值。

添加一个json文件appsettings.custom.json

{
  "BlogSettings": {
    "Title": "xxx博客",
    "Subtitle": "随便写点什么",
    "Url": "http://www.baidu.com",
    "Logo": "/upload/Pictures/global/Logo_40.PNG",
    "Abstract": "<b>随便写点什么!!!</b>",
    "LogoText": "XXXXBlog",
    "Keywords": ".NET,哈哈哈",
    "Description": ".NET,哈哈哈",
    "Statistics": null,
    "Footer": "",
    "QQAppId": null,
    "QQAppKey": null
  }
}

对应类

   /// <summary>
    /// 博客设置
    /// </summary>
    public class BlogSettingsViewModel
    {
        /// <summary>
        /// 网站标题
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 副标题
        /// </summary>
        public string Subtitle { get; set; }
        /// <summary>
        /// 网站链接
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 网站logo
        /// </summary>
        public string Logo { get; set; }
        /// <summary>
        /// 简介
        /// </summary>
        public string Abstract { get; set; }
        /// <summary>
        /// 网站首页显示logo
        /// </summary>
        public string LogoText { get; set; }
        /// <summary>
        /// 网站关键词
        /// </summary>
        public string Keywords { get; set; }
        /// <summary>
        /// 网站描述
        /// </summary>
        public string Description { get; set; }
        /// <summary>
        /// 第三方统计代码
        /// </summary>
        public string Statistics { get; set; }
        /// <summary>
        /// 页脚
        /// </summary>
        public string Footer { get; set; }
        /// <summary>
        /// qq登陆Id
        /// </summary>
        public string QQAppId { get; set; }
        /// <summary>
        /// qq登陆key
        /// </summary>
        public string QQAppKey { get; set; }
    }

Startup

 //绑定博客设置json节点
 services.ConfigureWritable<BlogSettingsViewModel>(Configuration.GetSection("BlogSettings"), "appsettings.custom.json");

Program添加

WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config => config.AddJsonFile("appsettings.custom.json", optional: true, reloadOnChange: true))
.UseStartup<Startup>()
.Build();

添加接口IWritableOptions 实现IOptionsSnapshot

 public interface IWritableOptions<T> : IOptionsSnapshot<T> where T : class, new()
    {
        
        void Update(Action<T> applyChanges);
        
    }

IWritableOptions实现类WritableOptions

 public class WritableOptions<T> : IWritableOptions<T> where T : class, new()
    {
    
        private readonly IHostingEnvironment _environment;
        private readonly IOptionsMonitor<T> _options;
        private readonly string _section;
        private readonly string _file;
        
        public WritableOptions(
            IHostingEnvironment environment,
            IOptionsMonitor<T> options,
            string section,
            string file)
        {
            _environment = environment;
            _options = options;
            _section = section;
            _file = file;
        }

        public T Value => this._options.CurrentValue;

        //public T CurrentValue => this._options.CurrentValue;

        public T Get(string name) => _options.Get(name);

        //public IDisposable OnChange(Action<T, string> listener)
        //{
        //    throw new NotImplementedException();
        //}

        public void Update(Action<T> applyChanges)
        {
            var fileProvider = _environment.ContentRootFileProvider;
            var fileInfo = fileProvider.GetFileInfo(_file);
            var physicalPath = fileInfo.PhysicalPath;

            var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
            var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
                JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());

            applyChanges(sectionObject);

            jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
            File.WriteAllText(physicalPath, JsonConvert.SerializeObject(jObject, Formatting.Indented));
        }
    }

    /// <summary>
    /// 把json文件节点绑定到类的扩展方法,具有修改功能
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static void ConfigureWritable<T>(
            this IServiceCollection services,
            IConfigurationSection section,
            string file = "appsettings.json") where T : class, new()
        {
            services.Configure<T>(section);
            services.AddTransient<IWritableOptions<T>>(provider =>
            {
                var environment = provider.GetService<IHostingEnvironment>();
                var options = provider.GetService<IOptionsMonitor<T>>();
                
                return new WritableOptions<T>(environment, options, section.Key, file);
            });
        }
    }

使用:

[Area("admin")]
    public class BlogSettingsController : AdminBaseController
    {
        private IWritableOptions<BlogSettingsViewModel> _option;
        public BlogSettingsController(IWritableOptions<BlogSettingsViewModel> option)
        {
            _option = option;

        }
        // GET: /<controller>/
        public IActionResult Index()
        {
          
            var entity = _option.Value;
            return View(entity);
        }
        /// <summary>
        /// 保存网站设置,这里保存到json文件里面。
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Save(BlogSettingsViewModel model)
        {
            
            try
            {
                //这里会导致多线程操作同个文件
                _option.Update(opt => {
                    opt.Title = model.Title;
                    opt.Logo = model.Logo;
                    opt.Subtitle = model.Subtitle;
                    opt.Url = model.Url;
                    opt.Abstract = model.Abstract;
                    opt.Keywords = model.Keywords;
                    opt.Description = model.Description;
                    opt.LogoText = model.LogoText;
                    opt.QQAppId = model.QQAppId;
                    opt.Statistics = model.Statistics;
                    opt.QQAppKey = model.QQAppKey;
                });
                return Json(new Response() { Code = ResponseCode.Success, Message = "保存成功!" });
            }
            catch(Exception ex)
            {
                return Json(new Response() { Code = ResponseCode.Fail, Message = ex.Message });
            }
            
        }

        
    }

 




以上是关于学习Net Core 2.0 做博客 操作json文件读写的主要内容,如果未能解决你的问题,请参考以下文章

如何在 net-core 2.0 中手动解析 JSON 字符串

来腾讯云开发者实验室 学习.NET Core 2.0

如何在.Net Core 2.0 App中读取appsettings.json

Json.Net 在.Net Core 2.0 中序列化DataSet 问题

Handle Refresh Token Using ASP.NET Core 2.0 And JSON Web Token

从 appsettings.json 获取 ConnectionString,而不是在 .NET Core 2.0 App 中硬编码