Setting Path and Expiration for session cookie in asp.net
Anything I have tried didn't work. Currenly I have following code to change asp.net session cookie expiration date and path, but asp doesn't want to listen to me. I sends same cookie in Set-Cookie header t开发者_StackOverflow社区wo times sometimes, sometimes it sends it's default cookie ignoring path and expiration date, sometimes it sends everything as expected, and sometimes it doesn't send Set-Cookie at all. What should I do. This drives me nuts :(
My code in Global.asax
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
/// only apply session cookie persistence to requests requiring session information
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
var sessionState = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
var cookieName = sessionState != null && !string.IsNullOrEmpty(sessionState.CookieName)
? sessionState.CookieName
: "ASP.NET_SessionId";
var timeout = sessionState != null
? sessionState.Timeout
: TimeSpan.FromMinutes(20);
/// Ensure ASP.NET Session Cookies are accessible throughout the subdomains.
if (Request.Cookies[cookieName] != null && Session != null && Session.SessionID != null)
{
Response.Cookies[cookieName].Value = Session.SessionID;
Response.Cookies[cookieName].Path = Request.ApplicationPath;
Response.Cookies[cookieName].Expires = DateTime.Now.Add(timeout);
}
}
}
Maybe if you try using the system call, and not direct change the cookies..
HttpContext.Current.Session.Timeout = 20;
update
After your comments, and from what you say to me, is that you try to use the same cookie, for 2 different applications, and set different time outs. But asp.net can keep only one session for every cookie. To solve that you must use 2 different named cookies, and not different cookie path.
On each application directory, on web.config, change the
<sessionState cookieName="AppSessionCookieName" ..>
Reference for more infos
https://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.100)
Hope this solve the problem.
精彩评论