asp.net Web站点风格切换的实现

2019-05-12 01:02:50王冬梅

    }

    // 根据页面路径获取其对应的 masterPage 的路径
    public string GetMasterPage(string userTheme){

       // 获取当前页面路径
       string pagePath = context.Request.Path;

       // 用于定位page结点的 XPath
       string xpath = "style[@theme='" + userTheme + "']" + "/masterPages/page[@path='" + pagePath.ToLower() + "']";

       // 获取与path属性相匹配的page结点
       XmlNode pageNode = node.SelectSingleNode(xpath);

       string master;
       if (pageNode != null) {
           // 获取page结点的 master属性的值
           master = pageNode.Attributes["master"].Value;
           return prepareMasterPath(master, userTheme);
       } else
           return null;
    }

    // 获取 Master Page 的路径
    // MasterPagePath = 跟路径 + Theme路径 + 模板路径
    private string prepareMasterPath(string masterPath, string userTheme) {
       string path;

       if (node.Attributes["masterRoot"] != null)
           path = node.Attributes["masterRoot"].Value + "/" + userTheme + "/" + masterPath;
       else {
           if (userTheme != null) {
              path = "~/" + userTheme + "/" + masterPath;
           } else {
              path = "~/" + masterPath;
           }
       }
       return path;
    }
}

这个类提供了一些简单的对XmlNode的操作,对styleTemplates结点进行了映射,这里需要明确两个概念:默认风格 和 用户风格:

默认风格,指的是站点管理员 或者 博主设置的风格,也就是Web.Config 中styleTemplates结点的Default属性。 用户风格,用户设置的风格,页面的实际显示是根据用户风格而 不是默认风格。当用户没有设置风格时,才显示默认风格。

很显然,这个类处理的所有的均是默认风格,我们来看一下它的几个主要方法和属性: