标签:
在商城网站中,用户中心的每个页面都要几乎都要涉及对用户是否登录的判断,为了减少代码重写,可采用切片编程
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcWeb.Public { public class IsLoginCheckAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { string returnUrl = filterContext.RequestContext.HttpContext.Request.Path; HttpCookie cookie = filterContext.RequestContext.HttpContext.Request.Cookies[SystemConfig.UserId]; int uid = cookie== null ? 0 : Convert.ToInt32(cookie.Value); if (uid == 0) { filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary( new { controller = "user", action = "login", returnurl = returnUrl }) ); } else { base.OnActionExecuting(filterContext); } } } public class IsShopLoginCheckAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { string returnUrl = filterContext.RequestContext.HttpContext.Request.Path; HttpCookie shopCookie = filterContext.RequestContext.HttpContext.Request.Cookies[SystemConfig.ShopID]; int shopid = shopCookie == null ? 0 : Convert.ToInt32(shopCookie.Value); if (shopid == 0) { HttpCookie cookie = filterContext.RequestContext.HttpContext.Request.Cookies[SystemConfig.UserId]; int uid = cookie == null ? 0 : Convert.ToInt32(cookie.Value); if (uid == 0) { filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary( new { controller = "shop", action = "login", returnurl = returnUrl }) ); } else { #region 店铺信息 Dictionary<string, object> param = new Dictionary<string, object>(); param.Add("uid", uid); string shopurl = RouteManager.GetApiRoute("Shop", "SingleShopByUID", param); DDGW.VIEWMODEL.Shops shop = Newtonsoft.Json.JsonConvert.DeserializeObject<DDGW.VIEWMODEL.Shops>(Business.Basic.Shop.ShopList.PostShop(shopurl)); #endregion if (shop.ShopsID > 0) { shopCookie = new HttpCookie(SystemConfig.ShopID, shop.ShopsID.ToString()); filterContext.RequestContext.HttpContext.Response.SetCookie(shopCookie); base.OnActionExecuting(filterContext); } else { filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary( new { controller = "shop", action = "login", returnurl = returnUrl }) ); } } } else { base.OnActionExecuting(filterContext); } } } }
使用时:
[HttpGet] [IsLoginCheck] public ActionResult Comment(int uid) { IList<SubOrders> noComments = new List<SubOrders>(); #region 用户未评价子订单 noComments = UserList.Instance.NoCommentOrders(uid); #endregion this.ViewBag.no = noComments; this.ViewBag.uid = uid; return View(); }
标签:
原文地址:http://www.cnblogs.com/xbblogs/p/4795120.html