Good day..! I have some issue getting the value of my cookie when called in a class..
here's my code in my default.aspx.. I can retrieve the value on the when inside the aspx page
HttpCookie myCookie = new HttpCookie("SAMPLE");
myCookie["value"] = HttpUtility.UrlEncode(value);
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
if (Request.Cookies["SAMPLE"] != null)
{
string userSettings;
if (Request.Cookies["SAMPLE"]["value"] != null)
{ userSettings = Request.Cookies["SAMPLE"]["value"]; }
}
But when i called the cookie inside a class using this code HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["SAMPLE"]["value"]) it doesn't have any value.. Any idea..? Hope to hear from you soon..
Regards,
Link
You can replace with Response
....
Response.Cookies.Add(myCookie);
if (Response.Cookies["SAMPLE"] != null)
{
...
}
Related
My application has a Session Fixation Vulnerability. To fix that vulnerability, I am changing the session id after login.
I am having below web pages in different folders Master and Transaction.
~/Master/Login.aspx : After the credentials validated, I am setting
Response.Cookies["ASPFIXATION"].Value ="xyz";
Session["ASPFIXATION"] = "xyz"
and redirect to ~/Master/Home.aspx
~/Master/Home.aspx : In this page, I am checking the session value with the cookie value on page load event.
string cookie_value = string.Empty;
string session_value = string.Empty;
if (Request.Cookies["ASPFIXATION"] != null)
cookie_value = Request.Cookies["ASPFIXATION"].Value;
if (HttpContext.Current.Session["ASPFIXATION"] != null)
session_value = HttpContext.Current.Session["ASPFIXATION"].ToString();
if (cookie_value != g_SessionFix)
{
if (Request.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = null;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-1);
}
if (Request.Cookies["ASPFIXATION"] != null)
{
Response.Cookies["ASPFIXATION"].Value = null;
Response.Cookies["ASPFIXATION"].Expires = DateTime.Now.AddDays(-1);
}
Response.Redirect("~/Master/Login.aspx", false);
}
Here the Session has the value and it is validated.
~/Transaction/Report.aspx : If i redirect to this page and have to check the same session and cookie value logic in this page load. But here the value of HttpContext.Current.Session["ASPFIXATION"] is null and value of HttpContext.Current.Session.IsNewSession also true
Try to reassign the value after reading the values, sometimes it clears the values after reading from the session:
if (Request.Cookies["ASPFIXATION"] != null)
{
cookie_value = Request.Cookies["ASPFIXATION"].Value;
Request.Cookies["ASPFIXATION"].Value = cookie_value;
}
if (HttpContext.Current.Session["ASPFIXATION"] != null)
{
session_value = HttpContext.Current.Session["ASPFIXATION"].ToString();
HttpContext.Current.Session["ASPFIXATION"] = session_value;
}
If it still doesn't work for you then you have one other option to do it,
if your session data is not confidential then try to pass it in query string and on page redirection retrieve this value.
Response.Redirect("~/Master/Login.aspx?data=" + session_value +");
All i want to save instance of a class in a cookie just to check something.
Here is my code
class khurram {
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1;
}
but 'tcook' is not present. what am i doing wrong i don't understand.
i also tried
[serializable]
class khurram {
public string str1{get;set;};
}
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1;
please help.
thanks in advance
The Value property is defined to be of type string - in both of your examples, you appear to be trying to give it a class khurram
Someething like this may work better for you:
class khurram {
public string str1{get;set;};
}
// later ...
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1.str1;
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Response.Write("<p> The cookie has been written.");
The question is quite straightforward:
How to replace a HttpCookie in MVC3? (Assuming we have access to the HttpContext instance)
Use SetCookie
var cookie = Request.Cookies["cookieName"];
if (cookie != null)
{
cookie.Value = "new value";
Response.SetCookie(cookie);
}
I've got a logout.aspx that is called when the user clicks logout and there is where I want to delete the cookies but it just won't do it...
public partial class LogoutUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie;
cookie = Request.Cookies.Get("Basket");
if (cookie == null)
{
cookie = new HttpCookie("Basket");
}
foreach (string item in cookie.Values.AllKeys)
{
Response.Cookies[item].Expires = DateTime.Now.AddDays(-1);
}
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies["Basket"].Expires = DateTime.Now.AddYears(-1);
Session.Abandon();
Response.Redirect("~/Default.aspx");
}
}
The cookie stores the values in the basket but after logging out I can still access the basket I don't know what's wrong.
Here is some relevant documentation.
I believe your mistake is in this line:
if (cookie == null)
You're checking for null, rather than checking for not null. Thus,
HttpCookie cookie;
cookie = Request.Cookies.Get("Basket");
if (cookie != null)
{
cookie = new HttpCookie("Basket");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
Response.Redirect("~/Default.aspx");
should do the trick.
Hope this is helpful.
Could it be this ?
Session identifiers for abandoned or expired sessions are recycled by default. That is, if a request is made that includes the session identifier for an expired or abandoned session, a new session is started using the same session identifier. You can disable this by setting regenerateExpiredSessionId attribute of the sessionState configuration element to true. For more information, see Session Identifiers.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon.aspx
I have built a shopping cart that uses Session State to keep the shopping cart data while the user is browsing the store.
I have an issue where if I leave the browser window open for a long time on step1 of the shopping cart, then press "go to step 2", my actions throw an error because the step2 action assumes the session hasn't expired and the ShopCart object is in the correct state.
I would like this scenario to be nicer for my users, but I think i need to somehow detect if the session has expired so that on next request I can throw them to Step1.
I found the following code that claims to to solve the problem, but it doesn't work for me.
The IsNewSession condition is true but the condition
if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) {
// handle expired session
}
always returns false and it never handles the invalid session. I'm confused.
Is this possible in ASP.NET (and MVC)?
Way 1
Put this code in the Init / Load event of Page 2...
if (Context.Session != null)
{
if (Context.Session.IsNewSession)
{
string sCookieHeader = Request.Headers["Cookie"];
if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
if (Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
Response.Redirect("Error Page");
}
}
}
Way 2
Alternative you can check whether the Session object exists before proceeding to work with it in Page 2, like this:
if (Session["Key"] != null)
{
Object O1 = (Object) Session["Key"];
}
else
{
Response.Redirect("ErrorPage.aspx");
}
The King 's answer does not work for me. I have added FormsAuthentication.SignOut() in OnActionExcuting(). The Response.Redirect will not work!
if (Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
This is my complete method
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
if (ctx.Session != null)
{
// check if a new session id was generated
if (ctx.Session.IsNewSession)
{
// If it says it is a new session, but an existing cookie exists, then it must
// have timed out
string sessionCookie = ctx.Request.Headers["Cookie"];
if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
{
string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
if (ctx.Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
RedirectResult rr = new RedirectResult(loginUrl);
filterContext.Result = rr;
//ctx.Response.Redirect("~/Home/Logon");
}
}
}
base.OnActionExecuting(filterContext);
}
}
You need to create the Session_OnEnd method In Global.asax.cs file in your project.
this is my code and I am able to Detecting Session expiry on ASP.NET MVC
protected void Session_OnEnd(object sender, EventArgs e)
{
int userid = 0;
userid = Convert.ToInt32(Session["UserID"]);
if (userid != 0)
{
var userActivity = DependencyResolver.Current.GetService<IUserRepo>();
var responce = userActivity.LogOutUsers(userid);
if (responce == true)
{
Session.Clear();
Session.Abandon();
}
}
}
more