public async Task <IActionResult> WriteArticle(WriteArticleDto model) { //根据model中的category来决定存储的文件路径 var fullPath = Path.Combine(_webHost.WebRootPath, "md\\" + model.Category + "\\" + model.Id + ".md"); //Console.WriteLine(fullPath); //如果没有这个md文件,新建一个article存入数据库,写入对应位置 if (!System.IO.File.Exists(fullPath)) { var article = new Article(); article.Id = model.Id; article.Title = model.Title; var catagory = _db.Categories.Where(c => c.CategoryName == model.Category).FirstOrDefault(); article.CategoryId = catagory.Id; article.Category = catagory; var user = await _userManager.GetUserAsync(HttpContext.User); article.Author = user.Email; article.URL = fullPath; await _db.AddAsync(article); await _db.SaveChangesAsync(); } using (var writer = new StreamWriter(fullPath)) { await writer.WriteAsync(model.Content); await writer.FlushAsync(); } return(View(model)); }
public async Task <string> Publish(WriteArticleDto model) { var now = DateTime.Now; //先根据Model里的id从数据库中找文章, var article = _db.Articles.Find(model.Id); //如果没找到,说明这是第一次保存(新建文章且没有按过保存),直接调用上一个方法 if (article == null) { await WriteArticle(model); } //如果找到了,说明之前保存过了,需要比较两个时间来决定是否再次写入md else { //Console.WriteLine("now:" + now); //Console.WriteLine("save time:" + model.SaveTime); TimeSpan saves = new TimeSpan(model.SaveTime.Ticks); TimeSpan nows = new TimeSpan(now.Ticks); TimeSpan diff = saves.Subtract(nows).Duration(); //Console.WriteLine(diff.TotalSeconds); if (diff.TotalSeconds > 5.0) { await WriteArticle(model); } } //无论找没找到,都要更新数据库(经过上面的操作,能保证再次根据Id一定能找到文章),并传回一个时间作为savetime var _article = _db.Articles.Find(model.Id); _article.HasPublished = true; _article.PublishTime = now; _db.Articles.Update(_article); _db.SaveChanges(); return(now.ToString()); }
public IActionResult WriteArticle(string cateName, string Title) { var model = new WriteArticleDto(); //如果title为空,说明是新建文章,返回一个指定id和文章类别的模型 //如果title不为空,则说明是编辑文章,根据title找到文章并返回有效模型 if (!string.IsNullOrEmpty(Title)) { model = _db.Articles.Where(a => a.Title == Title) .Select(a => new WriteArticleDto { Id = a.Id, Title = a.Title, Category = cateName }) .FirstOrDefault(); var fullpath = Path.Combine(_webHost.WebRootPath, "md\\" + cateName + "\\" + model.Id + ".md"); var res = new StringBuilder(); using (var reader = new StreamReader(fullpath)) { string content; while ((content = reader.ReadLine()) != null) { res.Append(content + '\n'); } } model.Content = res.ToString(); } else { model.Id = Guid.NewGuid(); model.Category = cateName; } ViewBag.Title = "Heyday-编辑文章"; return(View(model)); }