[转][MVC] 剖析 NopCommerce 的 Theme 机制
前言
目前开源的CMS、Blog或者电子商务站点,他们都有一个共同的亮点,无疑就是可任意切换皮肤,并且定制和扩展能力都非常强。在这方面PHP可以说做的是最好的。那么我们如何能够在我们的ASP.NET MVC站点下面实现任意切换皮肤呢?我立马想到最近流行的NopCommerce—开源的 ASP.NET MVC 电子商务站点。它提供了强大的换肤功能,可通过一键切换皮肤。那接下来,我们就一起去寻找换肤的秘诀,让我们的ASP.NET MVC站点也具有一键换肤的功能吧。让我们的ASP.NET MVC 站点可以随意 变 变 变!
换肤试用
先试用下Nop站点的换肤效果吧,打开Nop的源码,下载地址:http://nopcommerce.codeplex.com, 按照官方的Theme制作方法:http://www.nopcommerce.com/docs/72/designers-guide.aspx,拷贝默认的皮肤DarkOrange,并做相应处理。此处略去500字…
运行站点,首先呈现的是默认皮肤:
切换成我们刚才制作的皮肤:
换肤后的思考?
我们刚才制作皮肤的时候,将默认的皮肤文件夹下所有的文件拷贝到新的皮肤文件夹下面,并做了样式和HTML结构的修改。Nop应该是根据客户选择的皮肤定位到相应的皮肤文件夹下面,去找到View并加载出来。那实现换肤功能的关键就是: 根据用户选择的皮肤,ASP.NET MVC动态定位到皮肤文件夹下的View,并呈现出来。
做过ASP.NET MVC开发的朋友都知道,如果在Controller里面新建一个Action,但View不存在,页面肯定会报如下错误:
从异常信息可以看出,ASP.NET MVC内部有一种加载View的机制。如果我们能够扩展这种内部的加载View的机制,去按照我们的自定义逻辑根据不同的皮肤加载不同的View,那我们的站点就能够实现换肤功能了。实现这个功能的核心就是IViewEngine,资料介绍:http://www.cnblogs.com/answercard/archive/2011/05/07/2039809.html。该接口定义如下:
/// <summary>
/// Defines the methods that are required for a view engine.
/// </summary>
public interface IViewEngine
{
/// <summary>
/// Finds the specified partial view by using the specified controller context.
/// </summary>
ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache);
/// <summary>
/// Finds the specified view by using the specified controller context.
/// </summary>
ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache);
/// <summary>
/// Releases the specified view by using the specified controller context.
/// </summary>
/// <param name="controllerContext">The controller context.</param><param name="view">The view.</param>
void ReleaseView(ControllerContext controllerContext, IView view);
}
深入Nop,找到幕后黑手
那我们就到Nop的源代码中去寻找 IViewEngine 的实现类,看看运气如何? 运气不错,找到了3个Themeable****ViewEngine. 从名字就可以断定该类是用来实现Theme的。
(Tips: 借助Reshareper可轻松的查找某个接口的实现类,此外Reshareper还有其它的高级功能,谁用谁知道…)
先看看离接口IViewEngine最近的类—ThemeableVirtualPathProviderViewEngine,该类重写了FindView 和 FindPartialView 2个方法。我们以FindView为例进行研究吧,实际上FindPartialView跟FindView都差不多。
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
var mobileDeviceHelper = EngineContext.Current.Resolve<IMobileDeviceHelper>();
bool useMobileDevice = mobileDeviceHelper.IsMobileDevice(controllerContext.HttpContext)
&& mobileDeviceHelper.MobileDevicesSupported()
&& !mobileDeviceHelper.CustomerDontUseMobileVersion(); string overrideViewName = useMobileDevice ?
string.Format("{0}.{1}", viewName, _mobileViewModifier)
: viewName; ViewEngineResult result = FindThemeableView(controllerContext, overrideViewName, masterName, useCache, useMobileDevice);
// If we're looking for a Mobile view and couldn't find it try again without modifying the viewname
if (useMobileDevice && (result == null || result.View == null))
result = FindThemeableView(controllerContext, viewName, masterName, useCache, false);
return result;
}
查找View的重担放到了内部方法FindThemeableView中完成的,看看该方法的实现吧:
protected virtual ViewEngineResult FindThemeableView(ControllerContext controllerContext, string viewName, string masterName, bool useCache, bool mobile)
{
string[] strArray;
string[] strArray2;
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (string.IsNullOrEmpty(viewName))
{
throw new ArgumentException("View name cannot be null or empty.", "viewName");
}
var theme = GetCurrentTheme(mobile);
string requiredString = controllerContext.RouteData.GetRequiredString("controller");
string str2 = this.GetPath(controllerContext, this.ViewLocationFormats, this.AreaViewLocationFormats, "ViewLocationFormats", viewName, requiredString, theme, "View", useCache, mobile, out strArray);
string str3 = this.GetPath(controllerContext, this.MasterLocationFormats, this.AreaMasterLocationFormats, "MasterLocationFormats", masterName, requiredString, theme, "Master", useCache, mobile, out strArray2);
if (!string.IsNullOrEmpty(str2) && (!string.IsNullOrEmpty(str3) || string.IsNullOrEmpty(masterName)))
{
return new ViewEngineResult(this.CreateView(controllerContext, str2, str3), this);
}
if (strArray2 == null)
{
strArray2 = new string[0];
}
return new ViewEngineResult(strArray.Union<string>(strArray2));
}
这段代码读起来有点费力,又一次告诉大家命名的重要性,当然你不想让别人看懂你的代码那就是另外一回事哈。str2实际上是ViewPath,str3是MasterPagePath。其中内部方法GetPath是用来获取View的实际路径。我们来研究下GetPath的参数吧,其中最关键的是属性ViewLocationFormats和AreaViewLocationFormats。由于ThemeableVirtualPathProviderViewEngine是抽象类,我们看看派生自该类的ThemeableRazorViewEngine吧:
public ThemeableRazorViewEngine()
{
AreaViewLocationFormats = new[]
{
//themes
"~/Areas/{2}/Themes/{3}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Themes/{3}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Themes/{3}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Themes/{3}/Views/Shared/{0}.vbhtml", //default
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.vbhtml"
}; AreaMasterLocationFormats = new[]
{
//themes
"~/Areas/{2}/Themes/{3}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Themes/{3}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Themes/{3}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Themes/{3}/Views/Shared/{0}.vbhtml", //default
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.vbhtml"
}; AreaPartialViewLocationFormats = new[]
{
//themes
"~/Areas/{2}/Themes/{3}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Themes/{3}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Themes/{3}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Themes/{3}/Views/Shared/{0}.vbhtml", //default
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.vbhtml"
}; ViewLocationFormats = new[]
{
//themes
"~/Themes/{2}/Views/{1}/{0}.cshtml",
"~/Themes/{2}/Views/{1}/{0}.vbhtml",
"~/Themes/{2}/Views/Shared/{0}.cshtml",
"~/Themes/{2}/Views/Shared/{0}.vbhtml", //default
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml", //Admin
"~/Administration/Views/{1}/{0}.cshtml",
"~/Administration/Views/{1}/{0}.vbhtml",
"~/Administration/Views/Shared/{0}.cshtml",
"~/Administration/Views/Shared/{0}.vbhtml",
}; MasterLocationFormats = new[]
{
//themes
"~/Themes/{2}/Views/{1}/{0}.cshtml",
"~/Themes/{2}/Views/{1}/{0}.vbhtml",
"~/Themes/{2}/Views/Shared/{0}.cshtml",
"~/Themes/{2}/Views/Shared/{0}.vbhtml", //default
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml"
}; PartialViewLocationFormats = new[]
{
//themes
"~/Themes/{2}/Views/{1}/{0}.cshtml",
"~/Themes/{2}/Views/{1}/{0}.vbhtml",
"~/Themes/{2}/Views/Shared/{0}.cshtml",
"~/Themes/{2}/Views/Shared/{0}.vbhtml", //default
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.vbhtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.vbhtml", //Admin
"~/Administration/Views/{1}/{0}.cshtml",
"~/Administration/Views/{1}/{0}.vbhtml",
"~/Administration/Views/Shared/{0}.cshtml",
"~/Administration/Views/Shared/{0}.vbhtml",
}; FileExtensions = new[] { "cshtml", "vbhtml" };
}
看到这里你是否了解有些明白了?这里就是定义的查找View的路径的模版,程序(Nop和MVC默认实现都是相同的策略)会按照顺序依次查找View是否存在。
再来看看GetPath的实现吧:
protected virtual string GetPath(ControllerContext controllerContext, string[] locations,
string[] areaLocations, string locationsPropertyName, string name,
string controllerName, string theme, string cacheKeyPrefix,
bool useCache, bool mobile, out string[] searchedLocations)
{
searchedLocations = _emptyLocations;
if (string.IsNullOrEmpty(name))
{
return string.Empty;
}
string areaName = GetAreaName(controllerContext.RouteData); //little hack to get nop's admin area to be in /Administration/ instead of /Nop/Admin/ or Areas/Admin/
if (!string.IsNullOrEmpty(areaName) && areaName.Equals("admin", StringComparison.InvariantCultureIgnoreCase))
{
//admin area does not support mobile devices
if (mobile)
{
searchedLocations = new string[0];
return string.Empty;
}
var newLocations = areaLocations.ToList();
newLocations.Insert(0, "~/Administration/Views/{1}/{0}.cshtml");
newLocations.Insert(0, "~/Administration/Views/{1}/{0}.vbhtml");
newLocations.Insert(0, "~/Administration/Views/Shared/{0}.cshtml");
newLocations.Insert(0, "~/Administration/Views/Shared/{0}.vbhtml");
areaLocations = newLocations.ToArray();
} bool flag = !string.IsNullOrEmpty(areaName);
List<ViewLocation> viewLocations = GetViewLocations(locations, flag ? areaLocations : null);
if (viewLocations.Count == 0)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Properties cannot be null or empty.", new object[] { locationsPropertyName }));
}
bool flag2 = IsSpecificPath(name);
string key = this.CreateCacheKey(cacheKeyPrefix, name, flag2 ? string.Empty : controllerName, areaName, theme);
if (useCache)
{
var cached = this.ViewLocationCache.GetViewLocation(controllerContext.HttpContext, key);
if (cached != null)
{
return cached;
}
}
if (!flag2)
{
return this.GetPathFromGeneralName(controllerContext, viewLocations, name, controllerName, areaName, theme, key, ref searchedLocations);
}
return this.GetPathFromSpecificName(controllerContext, name, key, ref searchedLocations);
}
这里明显使用了缓存,所以大家不用担心每次读取View都要依次去进行IO操作去查找View引起的性能问题。
最后我们再来看看GetPathFromGeneralName的具体实现吧:
protected virtual string GetPathFromGeneralName(ControllerContext controllerContext,
List<ViewLocation> locations, string name, string controllerName, string areaName,
string theme, string cacheKey, ref string[] searchedLocations)
{
string virtualPath = string.Empty;
searchedLocations = new string[locations.Count];
for (int i = 0; i < locations.Count; i++)
{
string str2 = locations[i].Format(name, controllerName, areaName, theme);
if (this.FileExists(controllerContext, str2))
{
searchedLocations = _emptyLocations;
virtualPath = str2;
this.ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, virtualPath);
return virtualPath;
}
searchedLocations[i] = str2;
}
return virtualPath;
}
该方法会将参数Theme、Controller和Action传入上文提到的View路径模版,生成实际的路径,如果文件不存在,继续尝试下一个View路径模版。直到找到View存在的实际路径。
偷梁换柱,让MVC使用自定义的ViewEngine
Nop是通过在Global文件的事件Application_Start中注入以下代码:
//remove all view engines
ViewEngines.Engines.Clear();
//except the themeable razor view engine we use
ViewEngines.Engines.Add(new ThemeableRazorViewEngine());
总结
到这里,你是否已经知道了Nop实现Theme的奥秘?但又觉得过于复杂?其实Nop实现Theme的同时,还为Mobile和Admin管理后台做了很多特殊处理,所以代码看起来有点乱。那我们就来自己动手打造一个轻量级的ThemeViewEngine吧。预知后事,且听下回分解。
下一篇:[ASP.NET MVC 下打造轻量级的 Theme 机制]
[转][MVC] 剖析 NopCommerce 的 Theme 机制的更多相关文章
- 剖析Qt的事件机制原理
版权声明 请尊重原创作品.转载请保持文章完整性,并以超链接形式注明原始作者“tingsking18”和主站点地址,方便其他朋友提问和指正. QT源码解析(一) QT创建窗口程序.消息循环和WinMai ...
- asp.net core mvc剖析:启动流程
asp.net core mvc是微软开源的跨平台的mvc框架,首先它跟原有的MVC相比,最大的不同就是跨平台,然后又增加了一些非常实用的新功能,比如taghelper,viewcomponent,D ...
- 本版本延续MVC中的统一验证机制~续的这篇文章,本篇主要是对验证基类的扩展和改善(转)
本版本延续MVC中的统一验证机制~续的这篇文章,本篇主要是对验证基类的扩展和改善 namespace Web.Mvc.Extensions { #region 验证基类 /// <summary ...
- Spring MVC的工作原理和机制
Spring MVC的工作原理和机制 参考: springMVC 的工作原理和机制 - 孤鸿子 - 博客园https://www.cnblogs.com/zbf1214/p/5265117.html ...
- net core mvc剖析:启动流程
net core mvc剖析:启动流程 asp.net core mvc是微软开源的跨平台的mvc框架,首先它跟原有的MVC相比,最大的不同就是跨平台,然后又增加了一些非常实用的新功能,比如taghe ...
- 定制Asp.NET 5 MVC内建身份验证机制 - 基于自建SQL Server用户/角色数据表的表单身份验证
背景 在需要进行表单认证的Asp.NET 5 MVC项目被创建后,往往需要根据项目的实际需求做一系列的工作对MVC 5内建的身份验证机制(Asp.NET Identity)进行扩展和定制: Asp.N ...
- 深度剖析JDK动态代理机制
摘要 相比于静态代理,动态代理避免了开发人员编写各个繁锁的静态代理类,只需简单地指定一组接口及目标类对象就能动态的获得代理对象. 代理模式 使用代理模式必须要让代理类和目标类实现相同的接口,客户端通过 ...
- MVC特性路由的提供机制
回顾:传统路由是如何提供的? 我们知道最终匹配的路由数据是保存在RouteData中的,而RouteData通常又是封装在RequestContext中的,他们是在哪里被创建的呢?没错,回到了UrlR ...
- NopCommerce添加事务机制
NopCommerce现在最新版是3.9,不过依然没有事务机制.作为一个商城,我觉得事务也还是很有必要的.以下事务代码以3.9版本作为参考: 首先,IDbContext接口继承IDisposable接 ...
随机推荐
- Sass的使用和基础语法
sass安装 官网下载ruby的windows安装包,安装时勾选上添加到环境变量add ruby executables to your path.安装完成后打开命令行,ruby -v输出内容则安装完 ...
- 使用Reaver对WPS加密网络进行暴力破解
WPS状态探测 探测开启了WPS功能的AP,WPS Locked状态为NO的表示开启了WPS功能. wash -i wlan0mon PIN码获取 reaver -i wlan0mon -b MAC地 ...
- Httplistener Access Denied
HttpListener.Start() 会出现HttpListenerException, 显示拒绝访问 一般是因为有些计算机账户是没有权限创建 HttpListener服务, 但是可以注册一些规则 ...
- onMeasure流程解析
0.预备知识 我们的手机屏幕的布局其实是嵌套的,最外层是一个phoneWindow,这个view和手机屏幕一样大,里面是一个frameLayout,再里面才是我们自己写的布局文件. 我们在绘制控件前必 ...
- Linux中的硬链接和软链接
软链接和硬链接 命令ln ln是创建链接的命令: 创建硬链接:ln file link 创建软链接:ln -s file link 硬链接 硬链接(hard link)是Unix系统最早的创建链接的方 ...
- webView 显示一段 html 代码
1.布局文件 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:and ...
- android关于线程的那些事
今天发现之前自己一直有个误区,new Runnable(run()方法){}原来它不是一定创建一个线程 如果用主线程的handler去post(Runnable),他就不会创建子线程,而是在主线程上执 ...
- error=Error Domain=NSURLErrorDomain Code=-1003
我的情况:模拟器 可以返回数据 .真机不可以.我手机连接的同事的共享,我以为他的网段和后台的网段在同一个网段.一直在找错误,打开手机网络设置一看 ,原来不在同一网段.手机的网络必须要跟PC的在同一个 ...
- OC中runtime的使用
一.runtime简介* RunTime简称运行时.OC就是“运行时机制”,也就是在运行时候的一些机制,其中最主要的是消息机制.* 对于C语言,“函数的调用在编译的时候会决定调用哪个函数”.* 对于O ...
- CEF3可行性
Chromium Embedded Framework 顾名思义,内嵌式CHROME,详细的介绍参阅 http://yogurtcat.com/posts/cef/hello-cef.html 为什么 ...