MVC视图引擎优化

 

 

请首先看如下内容:

未找到视图"Index"或其母版视图,或没有视图引擎支持搜索的位置。搜索了以下位置
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

 

 

版权归二师弟和博客园共同所有,欢迎转载和分享知识。转载请注明出处!

Mvc4和mvc3是这样查找的,其中*.aspx和*.ascx以及*.vbhtml都是我们不需要的。

我们可以想象,这里不管采用什么办法,肯定至少4次访问文件系统并判断对应文件是否存在,才会找到我们的index.cshtml,这样的开销小型应用可以忽略,如果并发量千万级(总之很大,具体未测)肯定对性能有一定影响。

怎么避免,不要去查找*.aspx,*.ascx以及*.vbhtml?

经过几番折腾,我们成功找到了解决办法:

Mvc中有两个视图引擎,webformengine和razorengine,解决办法就是,确定不使用webform的情况下,移除webformengine,然后移除razorengine并添加改写了的razorengine。

 

移除的代码在global.ascx.cs的application_start方法中这样写:

ViewEngines.Engines.Clear();

重写razorengine的方法:

public class Engine : RazorViewEngine

{

public Engine( )

        {

            base.AreaViewLocationFormats = new string[]

            {

                "~/Areas/{2}/Views/{1}/{0}.cshtml",

                "~/Areas/{2}/Views/Shared/{0}.cshtml",

            };

            base.AreaMasterLocationFormats = new string[]

            {

                "~/Areas/{2}/Views/{1}/{0}.cshtml",

                "~/Areas/{2}/Views/Shared/{0}.cshtml",

                

            };

            base.AreaPartialViewLocationFormats = new string[]

            {

                "~/Areas/{2}/Views/{1}/{0}.cshtml",

                "~/Areas/{2}/Views/Shared/{0}.cshtml",

            };

            base.ViewLocationFormats = new string[]

            {

                "~/Views/{1}/{0}.cshtml",

                "~/Views/Shared/{0}.cshtml",

            };

            base.MasterLocationFormats = new string[]

            {

                "~/Views/{1}/{0}.cshtml",

                "~/Views/Shared/{0}.cshtml",

            };

            base.PartialViewLocationFormats = new string[]

            {

                "~/Views/{1}/{0}.cshtml",

                "~/Views/Shared/{0}.cshtml",

            };

            base.FileExtensions = new string[]

            {

                "cshtml",

            };

        }

}

然后添加改写的视图引擎:

ViewEngines.Engines.Add(new Engine());

版权归二师弟博客园共同所有,欢迎转载和分享知识。转载请注明出处!

最终application_start方法如下:

posted @   二师弟tl  阅读(2633)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示