zoukankan      html  css  js  c++  java
  • 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
    
        }
    }
  • 相关阅读:
    position之属性
    Grid网格布局
    position 属性指定了元素的定位类型
    注册表单
    简单页面
    自我介绍
    正则表达式
    Dom和Bom
    颜色和单位
    伪类和伪元素的区别
  • 原文地址:https://www.cnblogs.com/yechangzhong-826217795/p/4397559.html
Copyright © 2011-2022 走看看