Ejemplo n.º 1
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpSessionStateBase session = filterContext.HttpContext.Session;

            if (filterContext.HttpContext.Request.Cookies["userId"] != null && filterContext.HttpContext.Request.Cookies["userId"].Value.ToString().Trim() != "")
            {
                session["userId"] = filterContext.HttpContext.Request.Cookies["userId"].Value;
            }

            if (session["userId"] == null || (filterContext.HttpContext.Request.Cookies["token"] == null || filterContext.HttpContext.Request.Cookies["token"].Value.ToString().Trim() == ""))
            {
                session.Remove("Menu");
                session.Remove("MyMenu");
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary
                {
                    { "Controller", "Login" },
                    { "Action", "Index" }
                });
            }
            else
            {
                if (session["Menu"] == null)
                {
                    var    restClientContainer = new RestClientContainer(ConfigurationManager.AppSettings["ApiUrl"]);
                    var    dataRet             = restClientContainer.SendRequest <ResponseResult>("Accounts/GetMenu", RestSharp.Method.GET).Result.Data;
                    string json   = JsonConvert.SerializeObject(dataRet);
                    var    result = Helper <List <MenuViewModel> > .Convert(json);

                    session["Menu"] = result;
                }
            }
        }
Ejemplo n.º 2
0
 public static void Remove(this HttpSessionStateBase session, params string[] keys)
 {
     foreach (string key in keys)
     {
         session.Remove(key);
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Devuelve un objeto guardado temporalmente en la sessión
        /// </summary>
        /// <param name="session">session actual</param>
        /// <returns></returns>
        public static object Pop(HttpSessionStateBase session, Guid id)
        {
            var obj = session[PUSHPOP_DATA + id];

            session.Remove(PUSHPOP_DATA + id);
            return(obj);
        }
Ejemplo n.º 4
0
 public static void RemoveValue(this HttpSessionStateBase session, params SessionKey[] sessionKeys)
 {
     foreach (var sessionKey in sessionKeys)
     {
         session.Remove(sessionKey.ToString());
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// 检查验证码是否匹配
        /// </summary>
        /// <param name="session"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static bool IsVerifyCodeMatch(HttpSessionStateBase session, string code)
        {
            object data = session[VerifyCode];

            session.Remove(VerifyCode);
            return((null != data) && (data.ToString().Equals(code, StringComparison.OrdinalIgnoreCase)));
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 解除给定用户会话上的登录验证。
 /// </summary>
 /// <param name="session">会话。</param>
 public static void Deauthorize(HttpSessionStateBase session)
 {
     if (session != null)
     {
         session.Remove(SessionUsername);
     }
 }
Ejemplo n.º 7
0
        public static object Pull(this HttpSessionStateBase session, string name)
        {
            var tmp = session[name];

            session.Remove(name);
            return(tmp);
        }
Ejemplo n.º 8
0
        public static bool GetShowAuth(this HttpSessionStateBase Session)
        {
            var value = Session["ShowAuth"] as bool? == true;

            Session.Remove("ShowAuth");
            return(value);
        }
        /// <summary>Saves the specified values in the temporary data dictionary by using the specified controller context.</summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="values">The values.</param>
        /// <exception cref="T:System.InvalidOperationException">An error occurred the session context was being retrieved.</exception>
        public virtual void SaveTempData(
            ControllerContext controllerContext,
            IDictionary <string, object> values)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException(nameof(controllerContext));
            }
            HttpSessionStateBase session = controllerContext.HttpContext.Session;
            bool flag = values != null && values.Count > 0;

            if (session == null)
            {
                if (flag)
                {
                    throw new InvalidOperationException();
                }
            }
            else if (flag)
            {
                session["__ControllerTempData"] = (object)values;
            }
            else
            {
                if (session["__ControllerTempData"] == null)
                {
                    return;
                }
                session.Remove("__ControllerTempData");
            }
        }
Ejemplo n.º 10
0
        public virtual void Save(ControllerContext context, IDictionary <string, object> values)
        {
            HttpSessionStateBase session = context.Context.Session;
            bool isDirty = (values != null && values.Count > 0);

            if (session == null)
            {
                if (isDirty)
                {
                    throw Error.SessionStateDisabled();
                }
            }
            else
            {
                if (isDirty)
                {
                    session[SessionStateKey] = values;
                }
                else
                {
                    if (session[SessionStateKey] != null)
                    {
                        session.Remove(SessionStateKey);
                    }
                }
            }
        }
Ejemplo n.º 11
0
 // IoC-friendly constructor
 public StatefulStoragePerSession(HttpSessionStateBase session)
     : base((key) => session[key],
            (key, value) => session[key] = value,
            (key) => session.Remove(key)
            )
 {
 }
Ejemplo n.º 12
0
        public virtual void SaveTempData(ControllerContext controllerContext, IDictionary <string, object?> values)
        {
            if (controllerContext is null)
            {
                throw new ArgumentNullException(nameof(controllerContext));
            }

            HttpSessionStateBase session = controllerContext.HttpContext.Session;
            bool isDirty = (values != null && values.Count > 0);

            if (session is null)
            {
                if (isDirty)
                {
                    throw new InvalidOperationException(MvcResources.SessionStateTempDataProvider_SessionStateDisabled);
                }
            }
            else
            {
                if (isDirty)
                {
                    session[TempDataSessionStateKey] = values;
                }
                else
                {
                    // Since the default implementation of Remove() (from SessionStateItemCollection) dirties the
                    // collection, we shouldn't call it unless we really do need to remove the existing key.

                    if (session[TempDataSessionStateKey] != null)
                    {
                        session.Remove(TempDataSessionStateKey);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        /* 微信授权后跳转到的页面中通过code获取用户信息
         */
        public void SecondPage_RedirectUrl_GetUserInfoByCode(HttpSessionStateBase session, HttpResponseBase response, string code)
        {
            string url = @"https://api.weixin.qq.com/sns/oauth2/access_token" +
                         "?appid=" + _app_id +
                         "&secret=" + _app_secret +
                         "&code=" + code +
                         "&grant_type=authorization_code";

            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    throw new Exception("code为空");
                }
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage res = httpClient.GetAsync(url).Result;
                //string statusCode = response.StatusCode.ToString();
                if (res.IsSuccessStatusCode)
                {
                    string  result = res.Content.ReadAsStringAsync().Result;
                    JObject o      = JObject.Parse(result);
                    JToken  jt_errcode;
                    if (o.TryGetValue("errcode", out jt_errcode))
                    {
                        throw new Exception("微信服务器返回错误:【" + o["errcode"].ToString() + "】" + o["errmsg"].ToString());
                    }
                    else
                    {
                        WxWebApiRetAccessToken at = new WxWebApiRetAccessToken();
                        at.access_token  = o["access_token"].ToString();
                        at.expires_in    = int.Parse(o["expires_in"].ToString());
                        at.refresh_token = o["refresh_token"].ToString();
                        at.openid        = o["openid"].ToString();
                        at.scope         = o["scope"].ToString();
                        for (int i = 0; i < session.Keys.Count; ++i)
                        {
                            if (session.Keys[i] == _session_key_for_openid)
                            {
                                session.Remove(_session_key_for_openid);
                                break;
                            }
                        }
                        session.Add(_session_key_for_openid, at.openid);
                        response.Redirect(_root_url);
                        response.End();
                    }
                }
                else
                {
                    throw new Exception("服务器返回:" + res.StatusCode.ToString());
                }
            }
            catch (System.Exception ex)
            {
                response.Redirect(_error_url + "?error=" + HttpUtility.UrlEncode(ex.Message));
                response.End();
            }
        }
Ejemplo n.º 14
0
        /// <summary> Removes the <paramref name="functionToken"/> from the collection. </summary>
        /// <param name="functionToken">
        ///   The <see cref="WxeFunctionState"/> to be removed. Must not be <see langword="null"/> or empty.
        /// </param>
        protected void Remove(string functionToken)
        {
            ArgumentUtility.CheckNotNullOrEmpty("functionToken", functionToken);

            lock (_lockObject)
            {
                _session.Remove(GetSessionKeyForFunctionState(functionToken));
                _functionStates.Remove(functionToken);
            }
        }
Ejemplo n.º 15
0
 public static void RemoveKeys(this HttpSessionStateBase pair, string[] keys)
 {
     if (pair != null)
     {
         foreach (var key in keys)
         {
             pair.Remove(key);
         }
     }
 }
Ejemplo n.º 16
0
 public void Set(string key, bool value)
 {
     if (value)
     {
         _session[key] = true;
     }
     else
     {
         _session.Remove(key);
     }
 }
Ejemplo n.º 17
0
 public static void SetUsuarioLogado(this HttpSessionStateBase session, Usuario usuario)
 {
     if (usuario != null)
     {
         session[m_sesKeyUsuarioLogado] = usuario;
     }
     else
     {
         session.Remove(m_sesKeyUsuarioLogado);
     }
 }
        public static object GetAndRemove(this HttpSessionStateBase session, string key)
        {
            Assert.ArgumentNotNull(session, nameof(session));
            Assert.ArgumentNotNullOrEmpty(key, nameof(key));

            var sessionItem = session[key];

            session.Remove(key);

            return(sessionItem);
        }
Ejemplo n.º 19
0
 public ActionResult Hardware_req()
 {
     HttpSessionStateBase session = HttpContext.Session;
     HardwareListModel model = new HardwareListModel();
     model.Hardware = GetHardwareTypes();
     if(session["Customer_ID"] != null)
     {
         model.CustomerName = _customerService.GetCustomerById(Convert.ToInt32(session["Customer_ID"])).CustomerName;
         session.Remove("Customer_ID");
     }
     return View(model);
 }
Ejemplo n.º 20
0
 public ActionResult SignOut()
 {
     try {
         if (Session["user"] != null)
         {
             HttpSessionStateBase session = HttpContext.Session;
             session.Remove("user");
             session.Remove("role");
             if (Session["cart"] != null)
             {
                 session.Remove("cart");
             }
         }
     } catch (Exception e) {
         //chuyen toi trang bao loi
     }
     return(RedirectToRoute(new {
         controller = "Home",
         action = "Index",
         id = UrlParameter.Optional
     }));
 }
Ejemplo n.º 21
0
 /// <summary>
 /// Verify The Payment And Add The Order To The DataBase
 /// </summary>
 /// <param name="session"></param>
 /// <param name="creditCard"></param>
 /// <returns></returns>
 public static bool SetOrderToDatabase(this HttpSessionStateBase session, int creditCard)
 {
     if (creditCard != null && session["order"] != null) // check credit card
     {
         using (OrdersData db = new OrdersData())
         {
             Order order = (Order)session["order"];
             db.Add(order);
             session.Remove("order");
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 22
0
 public static void SafeRemove(this HttpSessionStateBase session, string key)
 {
     try
     {
         if (session != null && session[key] != null)
         {
             session.Remove(key);
         }
     }
     catch (Exception exc)
     {
         exc.Dump();
     }
 }
Ejemplo n.º 23
0
        public virtual IDictionary <string, object> Load(ControllerContext context)
        {
            HttpSessionStateBase session = context.Context.Session;

            if (session != null)
            {
                Dictionary <string, object> data = (session[SessionStateKey] as Dictionary <string, object>);
                if (data != null)
                {
                    session.Remove(SessionStateKey);
                }
            }
            return(new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase));
        }
Ejemplo n.º 24
0
 public ActionResult DeviceFailure()
 {
     HttpSessionStateBase session = HttpContext.Session;
     DeviceFailureListModel model = new DeviceFailureListModel();
     model.ProblemType = _ptypes.GetProblemTypeList();
     model.TroubleShooting = _tsh.GetTroubleShootingList();
     model.DeliveryDeviceSerialNumber = new List<SelectListItem>();
     if (session["Customer_ID"] != null)
     {
         model.CustomerName = _customerService.GetCustomerById(Convert.ToInt32(session["Customer_ID"])).CustomerName;
         session.Remove("Customer_ID");
     }
     return View(model);
 }
Ejemplo n.º 25
0
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            HttpSessionStateBase session = filterContext.HttpContext.Session;

            if (filterContext.HttpContext.Request.Cookies["userId"] != null && filterContext.HttpContext.Request.Cookies["userId"].Value.ToString().Trim() != "")
            {
                session["userId"] = filterContext.HttpContext.Request.Cookies["userId"].Value;
            }

            if (session["userId"] == null || (filterContext.HttpContext.Request.Cookies["token"] == null || filterContext.HttpContext.Request.Cookies["token"].Value.ToString().Trim() == ""))
            {
                session.Remove("Menu");
                session.Remove("MyMenu");
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Index" }));
                return;
            }
            var    language       = filterContext.HttpContext.Request.Cookies["Lang"] == null ? "en-US" : filterContext.HttpContext.Request.Cookies["Lang"].Value.ToString();
            string actionName     = filterContext.ActionDescriptor.ActionName;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            if (actionName.ToLower() == "Index".ToLower() && controllerName.ToLower() == "Home".ToLower())
            {
                session["PageName"] = language == "ar-EG"?"الشاشة الرئيسية":"Main Page";
                return;
            }
            var    querystring = filterContext.RequestContext.HttpContext.Request.QueryString;
            string parameter   = querystring["ScreenType"] == null ? null : Decoder.Decode(querystring["ScreenType"]);
            //IRestfulApi<List<bool>, List<bool>> res = new RestfulApi<List<bool>, List<bool>>(ConfigurationManager.AppSettings["ApiUrl"]);
            var restClientContainer = new RestClientContainer(ConfigurationManager.AppSettings["ApiUrl"]);

            //var menu = res.GetAsyncByGetVerb($"Role/CanShowPage/{language}/{controllerName}/{actionName}/{parameter}", null, filterContext.HttpContext.Request.Cookies["token"].Value.ToString()).Result;
            //if (menu != null ) session["PageName"] = menu;
            //if (menu == null )
            //{
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "UnAuthorize", action = "Index" }));
            // }
        }
Ejemplo n.º 26
0
        public static void AddWithTimeout(this HttpSessionStateBase session, string name, object value, TimeSpan expireAfter)
        {
            lock (session)
            {
                session[name] = value;
            }

            //add cleanup task that will run after "expire"
            Task.Delay(expireAfter).ContinueWith((task) => {
                lock (session)
                {
                    session.Remove(name);
                }
            });
        }
Ejemplo n.º 27
0
 public static string WasSignedInAs(this HttpSessionStateBase session, bool keep = true)
 {
     if (session != null)
     {
         var value = session[WasSignedInAsKey];
         if (!keep)
         {
             session.Remove(WasSignedInAsKey);
         }
         if (value != null)
         {
             return(value.ToString());
         }
     }
     return(null);
 }
Ejemplo n.º 28
0
 public static int FailedPasswordAttempts(this HttpSessionStateBase session, bool keep = true)
 {
     if (session != null)
     {
         var value = session[FailedPasswordAttemptsKey];
         if (!keep)
         {
             session.Remove(FailedPasswordAttemptsKey);
         }
         if (value is int)
         {
             return((int)value);
         }
     }
     return(0);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// 创建验证证并记录在Session中
        /// </summary>
        /// <param name="session"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static byte[] CreateVerifyImage(HttpSessionStateBase session, int length)
        {
            if (length < 2)
            {
                length = 2;
            }
            if (length > 10)
            {
                length = 10;
            }
            string code = CreateVerifyCode(length);

            session.Remove(VerifyCode);
            session.Add(VerifyCode, code);
            return(CreateVerifyGraphic(code));
        }
Ejemplo n.º 30
0
        public virtual IDictionary <string, object?> LoadTempData(ControllerContext controllerContext)
        {
            HttpSessionStateBase session = controllerContext.HttpContext.Session;

            if (session != null)
            {
                if (session[TempDataSessionStateKey] is Dictionary <string, object?> tempDataDictionary)
                {
                    // If we got it from Session, remove it so that no other request gets it

                    session.Remove(TempDataSessionStateKey);
                    return(tempDataDictionary);
                }
            }

            return(new Dictionary <string, object?>(StringComparer.OrdinalIgnoreCase));
        }