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

2021-05-16 01:29

阅读:520

标签:tab   链接   leo   indent   job   write   config   entity   hot   

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

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

对应类

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

Startup

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

Program添加

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

添加接口IWritableOptions 实现IOptionsSnapshot

 public interface IWritableOptions : IOptionsSnapshotwhere T : class, new()
    {
        
        void Update(Action applyChanges);
        
    }

IWritableOptions实现类WritableOptions

 public class WritableOptions : IWritableOptionswhere T : class, new()
    {
    
        private readonly IHostingEnvironment _environment;
        private readonly IOptionsMonitor _options;
        private readonly string _section;
        private readonly string _file;
        
        public WritableOptions(
            IHostingEnvironment environment,
            IOptionsMonitor 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 listener)
        //{
        //    throw new NotImplementedException();
        //}

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

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

            applyChanges(sectionObject);

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

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

使用:

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

        }
        // GET: //
        public IActionResult Index()
        {
          
            var entity = _option.Value;
            return View(entity);
        }
        /// 
        /// 保存网站设置,这里保存到json文件里面。
        /// 
        /// 
        /// 
        [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文件读写

标签:tab   链接   leo   indent   job   write   config   entity   hot   

原文地址:http://www.cnblogs.com/wyzy/p/7749715.html


评论


亲,登录后才可以留言!