在继续进行之前,我们来考虑这样一个问题:因为我们要根据用户选择的风格来动态地为页面加载主题和模板,那么用户信息(用户选择了什么风格)应该保存在哪里,从哪里获得呢?我们有很多的选择:可以使用Session、可以使用Cookie,还可以保存到数据库中。此时最好将这部分抽象出来,以便日后为不同的方法提供实现。我们定义一个接口 IUserStyleStrategy,它用来定义如何获取、设置用户风格,在AppCode中新建文件IUserStyleStragety.cs:
public interface IUserStyleStrategy{ void ResetUserStyle(string styleName); // 重新设置用户风格 string GetUserStyle(); // 获取用户风格 }
然后我在这里提供了一个基于Cookie的默认实现:
// 默认风格设置方法:使用Cookie记录 public class DefaultStyleStrategy : IUserStyleStrategy {
private string cookieName; // cookie名称 private HttpContext context;
public DefaultStyleStrategy(string cookieName){ this.cookieName = cookieName; context = HttpContext.Current; }
// 重新设置用户风格名称 public void ResetUserStyle(string styleName) { HttpCookie cookie; if(context.Request.Cookies[cookieName]!=null) cookie = context.Request.Cookies[cookieName]; else cookie = new HttpCookie(cookieName);
cookie.Value = context.Server.UrlEncode(styleName); cookie.Expires = DateTime.Now.AddHours(2); // 设置Cookie过期时间
context.Response.Cookies.Add(cookie);
// 因为风格(master page和theme)的动态设置只能在 PreInit 事件中 // 而Button的Click事件在PreInit事件之后,所以需要Redirect才可以生效 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属性赋值。
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|