how to set session value from cookies if session is expired
Microsoft Net Framework

how to set session value from cookies if session is expired


Step 1

Set value to cookies


 // Create a new cookie
                HttpCookie cookie = new HttpCookie(AppConstant.LoggedInCookies.ToString());
                // Set the value of the cookie
                cookie.Value = model.UserName;
                // Set other properties of the cookie (optional)
                cookie.Expires = DateTime.Now.AddDays(7); // Set an expiration time
                // Add the cookie to the response
                Response.Cookies.Add(cookie);

Step 2

get value from cookies and set to session object


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Routing;

namespace my.Web.UI.Controllers
{
   public class SessionExpiredFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var session = filterContext.HttpContext.Session;

            if (session[InvoiceAutomationSystems.Web.UI.Models.SessionItemsKey.LoggedInUser] == null)
            {
                if (filterContext.HttpContext.Request.Cookies[AppConstant.LoggedInCookies.ToString()] != null)
                {
                    session[InvoiceAutomationSystems.Web.UI.Models.SessionItemsKey.LoggedInUser] = filterContext.HttpContext.Request.Cookies[AppConstant.LoggedInCookies.ToString()].Value;
                }

            }

            /// user is logged in (the "loggedIn" should be set in Login action upon a successful login request)
            if (session[InvoiceAutomationSystems.Web.UI.Models.SessionItemsKey.LoggedInUser] != null)
                return;

            /// if the request is ajax then we return a json object
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    Data = "UnauthorizedAccess",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            /// otherwise we redirect the user to the login page
            else
            {
                var redirectTarget = new RouteValueDictionary { { "Controller", "Login" }, { "Login", "Login" } };
                filterContext.Result = new RedirectToRouteResult(redirectTarget);
            }
        }
    }
}
 

Share This with your friend by choosing any social account


Upcoming Articles
You may also read following recent Post
Copyright Future Minutes © 2015- 2024 All Rights Reserved.   Terms of Service  |   Privacy Policy |  Contact US|  Pages|  Whats new?
Update on: Dec 20 2023 05:10 PM