YbRapidSolution.MVC项目首页缓存没有起作用

Response.Cache.SetOmitVaryStar(true);

文件方面的内容,增加了这个语句

没有的话缓存没起作用,增加这个语句可提高系统性能。

HomeController:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using Glimpse.Mvc.Message;
using Yb.Data.Provider;
using YbRapidSolution.Cms.Drawing;
using YbRapidSolution.Core.IO;
using YbRapidSolution.Entities;
using YbRapidSolution.Mvc.Models;
using YbRapidSolution.Presenter;
using YbRapidSolution.Presenter.Controllers;
using YbRapidSolution.Services;
using YbRapidSolution.Services.Cms;

namespace YbRapidSolution.Mvc.Controllers.Security
{
    [AllowAnonymous]
    public class HomeController : Controller
    {
        #region 字段

        private readonly ICmsColumnService _colService;
        private readonly ICmsSettingService _settingService;
        private readonly ICmsPostService _postService;
        private readonly ICmsPollService _pollService;
        private readonly ICmsContentService _contentService;
        private readonly ICmsCommentService _commentService;
        private readonly IMediaProvider _mediaProvider;
        private readonly IMediaCacheProvider _mediaCacheProvider;

        #endregion

        #region 构造器

        public HomeController(ICmsColumnService colService,
            ICmsContentService contentService,
            ICmsCommentService commentService,
            IMediaProvider mediaProvider,
            IMediaCacheProvider mediaCacheProvider,
            ICmsSettingService settingService,
            ICmsPostService postService,
            ICmsPollService pollService)
        {
            _colService = colService;
            _settingService = settingService;
            _contentService = contentService;
            _commentService = commentService;
            _mediaProvider = mediaProvider;
            _mediaCacheProvider = mediaCacheProvider;
            _postService = postService;
            _pollService = pollService;
        }

        #endregion

        #region 私有方法

        private void SetService()
        {
            ViewBag.CmsSettingService = _settingService;
            ViewBag.CmsColumnService = _colService;
            ViewBag.CmsContentService = _contentService;
            ViewBag.CmsPostService = _postService;
            ViewBag.CmsPollService = _pollService;
            ViewBag.CmsCommentService = _commentService;
        }

        #endregion

        #region 首页方法

        // GET: /Logon/
        [AllowAnonymous]
        public ActionResult Index()
        {
            var setting =_settingService.Load();
            var home = _colService.GetHomeColumn()
                ?? new CmsColumn();

            var model = setting.GetPageModel(home);
            if (this.TempData.ContainsKey("HideLogin"))
            {
                model.HideLogin = (bool)this.TempData["HideLogin"];
            }
            else
            {
                model.HideLogin=false;
            }
            model.NavColumnId = model.ID;
            model.CurColumnId = model.ID;
            SetService();
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult Dashboard()
        {
            this.TempData["HideLogin"] = true;
            return RedirectToAction("Index");
        }

        #endregion

        #region 页面方法

        [AllowAnonymous]
        public ActionResult ColumnPage(string columnId,string navToId,int pageIndex=0)
        {
            var column = _colService.GetById(columnId);
            if (column == null)
                return RedirectToAction("Index");
            if (column.IsRedirect && !string.IsNullOrWhiteSpace(column.RedirectUrl))
            {
                return Redirect(column.RedirectUrl);
            }
            var path = "";
            switch (column.TemplateType)
            {
                case 0:
                    path = column.CoverTemplatePath;
                    break;
                case 1:
                    path = column.ListTemplatePath;
                    break;
                case 2:
                    path = column.ContentTemplatePath;
                    break;
                case 3:
                    path = column.SearchTemplatePath;
                    break;
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                return RedirectToAction("Index");
            }
            var setting = _settingService.Load();
            var model = setting.GetPageModel(column);
            model.CurColumnId = columnId;
            model.NavColumnId = navToId;
            model.PageIndex = pageIndex;
            SetService();
            return View(path, model);
        }
        /// <summary>
        /// 内容页
        /// </summary>
        /// <param name="columnId"></param>
        /// <param name="navToId"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult ContentPage(string id,string columnId, string navToId)
        {
            var column = _colService.GetById(columnId);
            if (column == null)
                return RedirectToAction("Index");
            if (column.IsRedirect && !string.IsNullOrWhiteSpace(column.RedirectUrl))
            {
                return Redirect(column.RedirectUrl);
            }
            var path = "";
            switch (column.TemplateType)
            {
                case 0:
                    path = column.CoverTemplatePath;
                    break;
                case 1:
                    path = column.ContentTemplatePath;
                    break;
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                return RedirectToAction("Index");
            }
            var setting = _settingService.Load();
            var model = setting.GetPageModel(column);
            model.CurColumnId = columnId;
            model.NavColumnId = navToId;
            model.CurContentId = id;
            SetService();
            return View(path, model);
        }

        #endregion

        #region 评论操作

        /// <summary>
        /// 添加评论
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [ValidateInput(false)]
        public JsonResult AddComment(CmsComment comment)
        {
            var result = new EasyUIMessage();
            ViewBag.CmsCommentService = _commentService;
            comment.ID = Guid.NewGuid().ToIdString();
            comment.CreatedDate = DateTime.Now;
            comment.CreatedFName = User.Identity.Name;

            var validResult = _commentService.Validate(comment);
            if (!validResult.IsValid)
            {
                result.success = false;
                result.msg = validResult.Errors[0].ErrorMessage;
                return Json(result);
            }
            var userReplyAudit = _settingService.Load().UserReplyAudit;
            comment.Cmd =  userReplyAudit ? Cmd.Save : Cmd.Publish;
            try
            {
                _commentService.Insert(comment);
                comment.Body = "";

                result.msg = userReplyAudit ? "评论提交成功,需管理员审核通过后才能显示" : "评论提交成功";
                result.success = true;
            }
            catch (Exception ex)
            {
                result.success = false;
                result.msg = ex.Message;
            }
            return Json(result);
        }
        /// <summary>
        /// 添加评论
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public PartialViewResult CommentList(string parentId, int pageSize = 20, int pageIndex = 0, string targetId=null)
        {
            ViewBag.PageIndex = pageIndex;
            ViewBag.CmsCommentService = _commentService;
            var items = _commentService.FindBy(c => c.ParentId == parentId, false,
                pageIndex, pageSize, c => c.OrderByDescending(d => d.CreatedDate));
            var model = new CmsPagerDataModel()
                {
                    Data = items,
                    ActionName=this.RouteData.Values["action"].ToString(),
                    ControllerName= this.RouteData.Values["controller"].ToString(),
                    RouteValues = new { parentId, targetId },
                    TargetId=targetId
                };
            SetService();
            return PartialView("_CommentList", model);
        }

        #endregion

        #region 文件操作

        [AllowAnonymous]
        [OutputCache(Duration = 600)]
        public FileResult GetImg(string id)
        {
            return GetFile(id);
        }
        /// <summary>
        /// Gets the thumbnail for the embedded resource with the given id. The thumbnail
        /// resources are specified in Piranha.Drawing.Thumbnails.
        /// </summary>
        /// <param name="id">Content id</param>
        /// <param name="size">The desired size</param>
        //[YbMvcAuthorize()]
        [AllowAnonymous]
        [OutputCache(Duration = 600, VaryByParam = "*")]
        public FileResult GetThumbnailBySize(string id, bool draft,int randNum=0, int size = 60)
        {
            return GetThumbnailBy(id,draft,randNum,size,size);
        }
        /// <summary>
        /// Gets the thumbnail for the embedded resource with the given id. The thumbnail
        /// resources are specified in Piranha.Drawing.Thumbnails.
        /// </summary>
        /// <param name="id">Content id</param>
        /// <param name="size">The desired size</param>
        [AllowAnonymous]
        [OutputCache(Duration = 600,VaryByParam="size")]
        public FileResult GetImgBySize(string id, int size = 60)
        {
            return GetThumbnailBySize(id, false, 0, size);
        }

        [AllowAnonymous]
        [OutputCache(Duration = 600, VaryByParam = "*")]
        public FileResult GetThumbnailBy(string id, bool draft, int randNum = 0, int width = 60, int height = 60)
        {
            Response.Cache.SetOmitVaryStar(true);
            //首先从缓存中获取
            var data = draft
                ? _mediaCacheProvider.GetDraft(id, width, height)
                : _mediaCacheProvider.Get(id, width, height);

            if (data == null)
            {
                //获取内容
                var content = _contentService.GetById(id, draft);
                if (content != null)
                {
                    Stream strm;
                    if (content.IsFolder)
                    {
                        //为文件夹,加载文件夹图标
                        var resource = Math.Min(width,height) <= 32
                            ? Thumbnails.GetByType("folder-small")
                            : Thumbnails.GetByType("folder");
                        strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
                    }
                    else if (content.ContentKind != ContentKind.Image)
                    {
                        //不为图片,根据类型加载资源图片
                        var type = Thumbnails.ContainsKeyByType(content.ContentType)
                            ? content.ContentType : "default";
                        var resource = Thumbnails.GetByType(type);
                        strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
                    }
                    else
                    {
                        //为图片,根据大下生成缩略图
                        var imgData = draft
                            ? _mediaProvider.GetDraft(id)
                            : _mediaProvider.Get(id);

                        if (imgData == null)
                        {
                            //不存在,使用默认图片
                            var resource = Thumbnails.GetByType("default");
                            strm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
                        }
                        else
                        {
                            strm = new MemoryStream(imgData);
                        }
                    }
                    var img = Image.FromStream(strm);
                    img = ImageUtils.Resize(img, width, height);
                    using (var mem = new MemoryStream())
                    {
                        img.Save(mem, ImageFormat.Png);
                        data = mem.ToArray();
                    }
                    strm.Close();

                    if (draft)
                        _mediaCacheProvider.PutDraft(id, data, width, height);
                    else
                        _mediaCacheProvider.Put(id, data, width, height);
                }
            }
            return File(data, "image/png");
        }

        /// <summary>
        /// Gets the thumbnail for the embedded resource with the given id. The thumbnail
        /// resources are specified in Piranha.Drawing.Thumbnails.
        /// </summary>
        /// <param name="id">Content id</param>
        /// <param name="size">The desired size</param>
        [AllowAnonymous]
        [OutputCache(Duration = 600, VaryByParam = "size")]
        public FileResult GetImgBy(string id, int width = 60, int height = 60)
        {
            return GetThumbnailBy(id, false, 0, width, height);
        }

        [AllowAnonymous]
        public FileResult GetFile(string id)
        {
            Response.Cache.SetOmitVaryStar(true);
            var content = _contentService.GetById(id);
            if (content == null || content.IsFolder)
                return null;
            var data=_mediaProvider.Get(id);
            if (data == null)
                return null;
            return File(data, content.ContentType, content.FileName);
        }

        [AllowAnonymous]
        public FileResult GetFileByPath(string fname)
        {
            Response.Cache.SetOmitVaryStar(true);
            var content = _contentService.GetByFName(fname);
            if (content == null || content.IsFolder)
                return null;
            var data = _mediaProvider.Get(content.ID);
            if (data == null)
                return null;
            return File(data, content.ContentType, content.FileName);
        }

        #endregion

        #region 图片轮播

        [AllowAnonymous]
        public PartialViewResult CarouseSide(string fname)
        {
            ViewBag.CmsContentService = _contentService;
            SetService();
            return PartialView("_CarouseSide", fname);
        }

        #endregion

        #region 问卷调查方法

        /// <summary>
        /// 提交问卷调查
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public PartialViewResult SubmitPoll()
        {
            if (!this.Request.Form.AllKeys.Contains("PollId"))
                return PartialView("_MsgDialog","提交失败:当前问卷调查不存在");
            var pollId = this.Request.Form.Get("PollId");
            if (string.IsNullOrWhiteSpace(pollId))
            {
                return PartialView("_MsgDialog", "提交失败:当前问卷调查不存在");
            }
            var poll = _pollService.GetById(pollId.Trim());
            if (poll==null)
            {
                return PartialView("_MsgDialog", "提交失败:当前问卷调查已被删除");
            }
            var date = DateTime.Now;
            if (!poll.PollPublished
                || (poll.StartDate.HasValue && poll.StartDate.Value > date)
                || (poll.EndDate.HasValue && poll.EndDate.Value < date))
            {
                return PartialView("_MsgDialog", "提交失败:当前问卷调查已关闭");
            }
            string ip="", cookie="", userName="";
            if(poll.LimitIP)
                ip = AccountController.GetIP4Address();
            if (poll.LimitCookie)
            {
                if (Request.Cookies.AllKeys.Contains(poll.ID))
                {
                    return PartialView("_MsgDialog", "提交失败:该问卷调查已提交,不允许重复提交");
                }
                cookie = poll.ID;
            }

            if (poll.LimitGuest)
            {
                if(!User.Identity.IsAuthenticated)
                    return PartialView("_MsgDialog", "提交失败:该问卷调查需登录后才能提交");
                userName = User.Identity.Name;
            }
            if (_pollService.Exists(ip, cookie, userName))
            {
                return PartialView("_MsgDialog", "提交失败:该问卷调查已提交,不允许重复提交");
            }

            var pollVoting = new CmsPollVoting
            {
                ID = Guid.NewGuid().ToIdString(),
                PollId = poll.ID,
                IP = ip,
                UserName = userName,
                Cookie = cookie,
                CmsPollVotingItem = new List<CmsPollVotingItem>(poll.CmsPollItem.Count)
            };

            foreach (var item in poll.CmsPollItem)
            {
                if (!this.Request.Form.AllKeys.Contains(item.ID))
                {
                    return PartialView("_MsgDialog", string.Format("提交失败:‘{0}’未选择。", item.Name));
                }
                var str = this.Request.Form.Get(item.ID);
                if (string.IsNullOrWhiteSpace(str))
                {
                    return PartialView("_MsgDialog", string.Format("提交失败:‘{0}’可选型未选择。", item.Name));
                }

                var votingItem = new CmsPollVotingItem
                {
                    ID = Guid.NewGuid().ToIdString(),
                    PollItemId = item.ID,
                    PollVotingId = pollVoting.ID
                };
                pollVoting.CmsPollVotingItem.Add(votingItem);

                votingItem.CmsPollVotingAnswer = new List<CmsPollVotingAnswer>(item.CmsPollAnswer.Count);
                //获取投票值
                var selectValues = str.Trim().Split(‘,‘).Distinct();
                //获取所有可选项
                var allAnswerIds = item.CmsPollAnswer.Select(c => c.ID).ToList();
                var dic=item.CmsPollAnswer.ToDictionary(c => c.ID);
                foreach (var value in selectValues)
                {
                    if (!dic.ContainsKey(value))
                    {
                        return PartialView("_MsgDialog", string.Format("提交失败:‘{0}’可选型未选择不存在。", item.Name));
                    }

                    var votingAnswer = new CmsPollVotingAnswer()
                    {
                        ID = Guid.NewGuid().ToIdString(),
                        PollAnswerId = value,
                        PollVotingItemId = item.ID,
                        Value = dic[value].Value
                    };
                    votingItem.CmsPollVotingAnswer.Add(votingAnswer);
                }
            }
            try
            {
                _pollService.Insert(pollVoting);
                if (cookie != "")
                {
                    HttpCookie curCookie = new HttpCookie(cookie)
                    {
                        Expires = DateTime.Now.AddYears(3)
                    };
                    System.Web.HttpContext.Current.Response.Cookies.Add(curCookie);
                }
                return PartialView("_MsgDialog", "问卷调查提交成功,谢谢您的参与");
            }
            catch(Exception er)
            {
                AuditLogApi.Error(er.Message, er);
                return PartialView("_MsgDialog", "提交失败:系统出现异常,请查看审计日志了解详细信息");
            }
        }
        [AllowAnonymous]
        public PartialViewResult ViewPollResult(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return PartialView("_MsgDialog", "当前问卷调查不存在");
            }
            var poll = _pollService.GetById(id.Trim());
            if (poll == null)
            {
                return PartialView("_MsgDialog", "当前问卷调查不存在");
            }
            if (!poll.ResultPublished)
            {
                return PartialView("_MsgDialog", "当前问卷调查暂未发布");
            }
            var total = poll.CmsPollVoting.Count;
            foreach (var item in poll.CmsPollItem)
            {
                foreach (var answer in item.CmsPollAnswer)
                {
                    answer.Count = item.CmsPollVotingItem
                        .SelectMany(c => c.CmsPollVotingAnswer)
                        .Count(c => c.PollAnswerId == answer.ID);
                    answer.Ratio = total == 0 ? 0m : answer.Count / (decimal)total;
                }
            }
            return PartialView("_PollResult", poll);
        }
        #endregion

    }
}
时间: 2024-11-10 07:15:47

YbRapidSolution.MVC项目首页缓存没有起作用的相关文章

YbRapidSolution.MVC项目首页分页没有起作用

@model YbRapidSolution.Mvc.Models.CmsPagerDataModel <nav> <ul class="pager"> <li class="@(Model.Data.IsFirstPage ? "disabled" : "")"> @(!Model.Data.IsFirstPage ? Html.ActionLink("首 页",Mod

谈谈MVC项目中的缓存功能设计的相关问题

本文收集一些关于项目中为什么需要使用缓存功能,以及怎么使用等,在实际开发中对缓存的设计的考虑 为什么需要讨论缓存呢? 缓存是一个中大型系统所必须考虑的问题.为了避免每次请求都去访问后台的资源(例如数据库),我们一般会考虑将一些更新不是很频繁的,可以重用的数据,通过一定的方式临时地保存起来,后续的请求根据情况可以直接访问这些保存起来的数据.这种机制就是所谓的缓存机制. 根据缓存的位置不同,可以区分为: 1.客户端缓存(缓存在用户的客户端,例如浏览器) 2.服务器断货(缓存在服务器中,可以缓存在内存

.net mvc中的缓存

今天我们聊一聊在.net mvc中的缓存是什么以及如何来实现缓存? 1.首先我们看一看什么缓存? 缓存就是数据交换的缓冲区(称作Cache),当某一硬件要读取数据时,会首先从缓存中查找需要的数据,如果找到了则直接执行,找不到的话则从内存中找.由于缓存的运行速度比内存快得多,故缓存的作用就是帮助硬件更快地运行.这里是指在电脑中的缓存,那么我们在看看在程序的中的缓存的是什么定义? 在程序中的缓存指的就是:客户端在第一次向服务器请求的数据的时候,服务器会根据客户端的请求来响应客户端所需要的数据,并同时

ASP.NET MVC 数据库依赖缓存的实现

当数据库中的信息发生变化的时候,应用程序能够获取变化的通知是缓存依赖得以实现的基础.应用程序可以通过轮询获取数据变化的信息,使用轮询的话也不可能重新查一次后再和以前的数据做比较,如果这样的话如果我一个表里面有1000行数据我要是读100次的话是不是得比较1000 x 100 次,显然这种方法是不可行的,那怎么办呢?大家都学过触发器吧,实现数据库依赖缓存的轮询机制就是通过触发器来实现的. 实现步骤简单分析:     首先创建一个用于记录监控信息的表,表的字段就两个一个是表名,一个是版本号.然后,对

第12章 MVC项目综述

一段废话:看懂.把代码敲一遍是不能把知识真正的学会的,学会一个知识:1.总结知识特性,2.举一反三运用 ---------------------------------------------------------- 注:在部署服务器时,应将配置文件中<compilation debug="false" targetframwork="4.0"> .debug必须为"false" -------------------------

MVC项目实践,在三层架构下实现SportsStore-01

SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管理.图像上传......是不错的MVC实践项目,但该项目不是放在多层框架下开发的,离真实项目还有一段距离.本系列将尝试在多层框架下实现SportsStore项目,并用自己的方式实现一些功能. 本篇为系列第一篇,包括: ■ 1.搭建项目■ 2.卸载Entity Framework组件,并安装最新版本■ 3.使用

MVC项目实践,在三层架构下实现SportsStore-01,EF Code First建模、DAL层等

http://www.cnblogs.com/darrenji/p/3809219.html 本篇为系列第一篇,包括: ■ 1.搭建项目■ 2.卸载Entity Framework组件,并安装最新版本■ 3.使用EF Code First创建领域模型和EF上下文■ 4.三层架构设计    □ 4.1 创建DAL层        ※ 4.1.1 MySportsStore.IDAL详解        ※ 4.1.2 MySportsStore.DAL详解 1.搭建项目 MySportsStore.

MVC 使用自定义缓存

MVC使用自定义缓存:首先我是在一个工具类库中新建一个缓存帮助类,比如这里我在Itcast.CMS.Common 类库中新建了一个CacheHelper.cs类 using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace

本地MVC项目发布到IIS服务器

0瞎扯 朋友们有时候我们写个一个web程序只能使用卡西尼服务器调试,下面我教大家发布到IIS服务器上(包括本地ISS7.5和远程服务器 IIS) 1.VS发布 a.点击web项目->发布 b.在发布->配置文件->新建 连接中选择文件系统,并选择发布文件要存放的地址 设置->配置:如下 设置完成后点击发布 发布好的目录 b.配置IIS 0.创建网站之前必须启动:W3SVC(World Wide Web Publishing Service)服务,作用:通过 Internet 信息服