简体   繁体   中英

Cookie is always Null C# ASP.NET MVC

I am using an AuthController with OnActionExecuting event that determines if the user logged in and if not then I send the user to the login page.

public class AuthController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // load session
        var LoginSession = Session[Constants.USER_SESSION_NAME];

        // load cookie
        HttpCookie LoginCookie = System.Web.HttpContext.Current.Request.Cookies[Constants.USER_COOKIE];

        // create cookie from session 
        if (LoginSession != null && LoginCookie == null)
        {
            var user = (UserLoginDto)LoginSession;

            CreateCookieFromSession(user);
        }

        // create session from cookie
        if (LoginSession == null)
        {
            if (LoginCookie != null)
            {
                if (!string.IsNullOrEmpty(LoginCookie.Value))
                    CreateSessionFromCookie(LoginCookie);
            }               
        }                 

        // if session does not exist send user to login page
        if (Session[Constants.USER_SESSION_NAME] == null)
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    {"controller", "Login"},
                    {"action", "Index"}
                }
            );
        }    
    }        

    private void CreateSessionFromCookie(HttpCookie cookieObj)
    {            
        UserLoginDto userDto = new UserLoginDto();

        userDto.Id = Convert.ToInt32(cookieObj.Value.Split('&')[0]);                    

        userDto = UserRepository.Get(userDto.Id);

        Session.Add(Constants.USER_SESSION_NAME, userDto);        
    }         

    private HttpCookie CreateCookieFromSession(UserLoginDto user)
    {
        HttpCookie cookie = Request.Cookies[Constants.USER_COOKIE];

        if (cookie == null)
        {
            cookie = new HttpCookie(Constants.USER_COOKIE);
            cookie.Value = user.Id.ToString();
            cookie.Values.Add("Name", Encryptor.encryptString(user.Name));
            cookie.Values.Add("Type", Encryptor.encryptString(user.Type));
            cookie.Values.Add("Token", user.Token);
            cookie.Values.Add("ProfilePictureName", user.ProfilePictureName);
            cookie.Values.Add("ProfilePicturePath", user.ProfilePicturePath);
        }

        cookie.Expires = DateTime.Now.AddYears(1);

        Response.Cookies.Add(cookie);

        return cookie;
    }
}

Every other controller but login extends AuthController.

public class HomeController : AuthController
{
    [HttpGet]
    public ActionResult Index()
    {            
        return View();
    }
}

The cookie is always Null when I try loading from the OnActionExecuting method. Can anyone spot the issue? I also tried creating the cookie in the LoginController, but still Null.

Hopefully this will help another developer. Finally figured it out. I have commented out some of the values since I do not need them and they might have made the cookie value too big. All of the values together must have exceeded the max size allowed which is 4096 Bytes , i believe.

private HttpCookie CreateCookieFromSession(UserLoginDto user)
{
    HttpCookie cookie = Request.Cookies[Constants.USER_COOKIE];

    if (cookie == null)
    {
        cookie = new HttpCookie(Constants.USER_COOKIE);
        cookie.Value = user.Id.ToString();
        //cookie.Values.Add("Name", Encryptor.encryptString(user.Name));
        //cookie.Values.Add("Type", Encryptor.encryptString(user.Type));
        cookie.Values.Add("Token", user.Token);
        //cookie.Values.Add("ProfilePictureName", user.ProfilePictureName); 
        //cookie.Values.Add("ProfilePicturePath", user.ProfilePicturePath); // base64 string (might have caused the issue)
    }

    cookie.Expires = DateTime.Now.AddYears(1);

    Response.Cookies.Add(cookie);

    return cookie;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM