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

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

       context.Response.Redirect(context.Request.Url.PathAndQuery);
    }

    // 获取用户自己设置的风格名称
    public string GetUserStyle() {     
       if (context.Request.Cookies[cookieName] != null) {
           string value = context.Request.Cookies[cookieName].Value;
           value = context.Server.UrlDecode(value);   // 避免出现中文乱码
           return value;
       } else
           return null;
    }
}

如果日后你需要将信息保存在数据库中,那么你只要重新实现一下这个接口就可以了:

// 如果将用户风格设置存储到了数据库中,可以实现这个接口
public class SqlStyleStrategy : IUserStyleStrategy {

    private int userId;          // 用户Id

    public SqlStyleStrategy(int userId){
       this.userId = userId;
       // ...
    }

    public void ResetUserStyle(string styleName) {
       throw new NotImplementedException();
    }

    public string GetUserStyle() {
       throw new NotImplementedException();
    }
}

PageBase 类:继承自Page的基类

因为所有的页面都要运行这样的一个逻辑:判断用户是否有设置风格,如果没有,使用Web.Config中设置的默认风格;如果设置了,使用用户风格。最后动态地给Page类的Theme属性和MasterPageFile属性赋值。

那么我们可以定一个基类,在这个基类中去做这件事,然后让所有的页面继承这个基类;又因为页面是一定要继承自System.Web.UI.Page类的,所以这个基类也必须继承自System.Web.UI.Page。现在在AppCode中再建一个文件 PageBase.cs:

// 供所有基类继承
public class PageBase : Page
{
    protected StyleTemplateConfiguration styleConfig;
    protected string userStyle;         // 用户设置的风格
    protected string userTheme;         // 用户设置的主题
    protected IUserStyleStrategy userStrategy; // 使用何种算法来获得用户自定义的信息
          
    protected override void OnPreInit(EventArgs e) {
       base.OnPreInit(e);