[英]Cookie is always Null C# ASP.NET MVC
我正在使用带有 OnActionExecuting 事件的 AuthController,该事件确定用户是否登录,如果没有,我将用户发送到登录页面。
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;
}
}
每隔一个 controller 但登录扩展 AuthController。
public class HomeController : AuthController
{
[HttpGet]
public ActionResult Index()
{
return View();
}
}
当我尝试从 OnActionExecuting 方法加载时,cookie 始终为 Null。 谁能发现这个问题? 我也尝试在 LoginController 中创建 cookie,但仍然是 Null。
希望这将有助于其他开发人员。 终于想通了。 我已经注释掉了一些值,因为我不需要它们,它们可能使 cookie 值太大。 我相信,所有值加在一起必须超过允许的最大大小,即4096 字节。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.