Cookie always return null in asp.net - asp.net

net web pages,in the first one, I wrote like below:
protected void lbXML_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("RequestedXML");
cookie["xmlContent"] = hide_XML.Value;
Response.Cookies.Add(cookie);
cookie.Expires = DateTime.Now.AddMinutes(20);
Response.Write("<script>window.open('XML_Editor.aspx', '_blank', 'toolbar=no, location=no, resizable=yes, width=800px, height=500px', true);</script>");
}
In XML_Editor.aspx, I wrote code like this:
protected void Page_Load(object sender, EventArgs e)
{
Page lastPage = (Page)Context.Handler;
if (!IsPostBack)
{
HttpCookie cookie = Request.Cookies["RequestedXML"];
if (cookie != null)
{
TextBox1.Text = cookie["xmlContent"];
}
}
}
the problem is that the cookie always return null to me in Page_Load in XML_Editor.aspx, why is that?

Your problem can be you code, try it:
HttpCookie cookie = new HttpCookie("RequestedXML");
cookie.Value =hide_XML.Value;
cookie.Expires = DateTime.Now.AddMinutes(20);
Response.Cookies.Add(cookie);
Response.Write("<script>window.open('XML_Editor.aspx', '_blank', 'toolbar=no, location=no, resizable=yes, width=800px, height=500px', true);</script>");
XML_Editor.aspx
Page lastPage = (Page)Context.Handler;
if (!IsPostBack)
{
var cookie = Request.Cookies["RequestedXML"];
if (cookie != null)
{
Response.Write(cookie.Value);
}
}

Related

How to stop opening a login page in (asp.net webforms) when user is already logged in the same browser in different tab

I have logged in as a user and it works fine , but when i try to open the login in a different tab in same browser it still goes to the login.aspx without the actual member page
Please help !
Aboutus.aspx
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Username"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
string Username = Session["Username"].ToString();
Label1.Text = Username;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("Login.aspx");
}
}
Login.aspx
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select COUNT(*)FROM [dbo].[Reg] WHERE Username='" + Login1.UserName + "' and Password=#pass");
cmd.Connection = con;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
////create an array of bytes we will use to store the encrypted password
Byte[] hashedBytes;
////Create a UTF8Encoding object we will use to convert our password string to a byte array
UTF8Encoding encoder = new UTF8Encoding();
////encrypt the password and store it in the hashedBytes byte array
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Login1.Password));
cmd.Parameters.AddWithValue("#pass", hashedBytes);
var username = Login1.UserName;
int OBJ = Convert.ToInt32(cmd.ExecuteScalar());
if (OBJ > 0)
{
if (username == "admin")
{
Session["Username"] = Login1.UserName;
Response.Redirect("AdminPanel.aspx");
}
else
{
Session["Username"] = Login1.UserName;
Response.Redirect("About.aspx");
}
}
else
{
Label1.Text = "Invalid username or password";
this.Label1.ForeColor = Color.Red;
}
}
}
}
In Page_Load of Login.aspx do this:
if(Session["Username"] != null)
{
string username = Convert.ToString(Session["Username"]);
if (username == "admin")
{
Response.Redirect("AdminPanel.aspx");
}
else
{
Response.Redirect("About.aspx");
}
}
Your page laod method on Loginpage must be like this
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Username"] == null)
{
}
else
{
Response.Redirect("index.aspx",false);
}
}
I hope this helps

Putting Data from Cookie into a List<string> with ASP.net

I'm trying to make a shoppingcart using a cookie.
Every item has a Id which is put into the cookie.
Now I'm trying to put my cookie values into a List but I can't really find how to do it.
I want every value to be in a seperate index, is this possible?
Making the cookie:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
Response.Cookies.Add(myCookie);
Adding a Id on buttonclick:
protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyTestCookie"].Values.Add("", "3");
Response.Write(Request.Cookies["MyTestCookie"].Values.ToString());;
}
Try this
public void SetCookiesList(List<string> listOfCookies)
{
var req = HttpContext.Current.Request;
HttpCookie cookie = req.Cookies["cookieName"];
if (cookie != null)
{
var cookieVal = cookie.Value;
if (!string.IsNullOrEmpty(cookieVal))
listOfCookies.Add(cookieVal);
}
}

Session is not being created...why?

On login page i have created the session like this.
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
if (Session["UserId"] != null)
{
Response.Redirect("~/client/ClientHome.aspx");
}
if (Request.QueryString["error"] != null)
{
loginuser.FailureText= "Please Login to visit the Page";
}
}
protected void loginuser_LoggedIn(object sender, EventArgs e)
{
if (Roles.IsUserInRole(loginuser.UserName, "admin"))
{
string username = loginuser.UserName;
DataSet ds = new DBUsers().GetUserId(username);
Guid userid = Guid.Parse(ds.Tables[0].Rows[0][0].ToString());
Session["UserId"] = userid;
Response.Redirect("Admin/Home.aspx");
}
else if (Roles.IsUserInRole(loginuser.UserName, "client"))
{
bool isPersistent = false;
string username = loginuser.UserName;
DataSet ds = new DBUsers().GetUserId(username);
Guid userid = Guid.Parse(ds.Tables[0].Rows[0][0].ToString());
Session["UserId"] = userid;
string userData = "ApplicationSpecific data for this user.";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// Redirect back to original URL.
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
}
here value of session is not null , it contains userid
but when the home page loads it says that the value of session is null
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
if (Session["UserId"] == null)
{
Response.Redirect("../Login.aspx?error=1");
}
}
why it enters inside if statement, why sesion value is null.

Using Global.asax to set/check session variable and redirect (for user testing)

I would like to add very simple, temporary security to my site.
I made a page at Home/UnderConstruction where people testing the site can enter a hard-coded password which will then set the "underconstruction" session variable to "false".
This is what I have so far, but it results in too many redirects:
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
string oc = underconstruction.ToString();
if (oc != "false") Response.Redirect("~/Home/UnderConstruction");
}
}
}
Is this close to what I would need to do?
Here is the code we got to work:
Controller Code for UnderConstruction View
public ViewResult UnderConstruction()
{
return View();
}
[HttpPost]
public ActionResult UnderConstruction(string ocp)
{
if (ocp == "mypassword")
{
Session["underconstruction"] = "false";
return RedirectToAction("Index", "Home");
}
else
{
Session["beingredirected"] = "false";
return View();
}
}
Global.Asax
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
HttpContext.Current.Session["beingredirected"] = "false";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
bool uc = false;
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
uc = Boolean.Parse(underconstruction.ToString());
}
bool redirected = false;
var beingredirected = HttpContext.Current.Session["beingredirected"];
if (beingredirected != null)
{
redirected = Boolean.Parse(beingredirected.ToString());
}
if (uc && !redirected)
{
if (Request.HttpMethod == "GET")
{
HttpContext.Current.Session["beingredirected"] = "true";
Response.Redirect("~/Home/UnderConstruction");
}
else if (Request.HttpMethod == "POST")
{
}
}
HttpContext.Current.Session["beingredirected"] = "false";
}
}
Is ~/Home/UnderConstruction in a different website? If not, wont it always redirect because oc will always be true? ie - do you also need to add a check for the page you're requesting so you can bypass the redirect if already going to the UnderConstruction page?
UPDATE
Not sure if checking the page name is a great idea, but something like this might work:
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
HttpContext.Current.Session["beingredirected"] = "false";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
bool uc = false;
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
uc = Boolean.Parse(underconstruction);
}
bool redirected = false;
var beingredirected = HttpContext.Current.Session["beingredirected"];
if (beingredirected != null)
{
redirected = Boolean.Parse(beingredirected);
}
if (uc && !redirected)
{
HttpContext.Current.Session["beingredirected"] = "true";
Response.Redirect("~/Home/UnderConstruction");
}
HttpContext.Current.Session["beingredirected"] = "false";
}
}
Note that I would clean that up, that example was to just give the general idea.
UPDATE
If you want to use roles as mentioned in the comments, then this article from ScottGu's Blog may help. Its a little more complicated, but has the added benefit of not introducing temporary code as the above solution will

asp.net cookies are getting overwritten

I have an asp.net web application with one drop down box containing language preferences (English, French). When I select French I write cookie as following -
protected void ddChoice_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("pref");
cookie.Value = ddChoice.SelectedValue;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddChoice.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddChoice.SelectedValue);
Server.Transfer(Request.Path);
}
and read this cookie in begin request as follows -
protected void Application_BeginRequest(object sender, EventArgs e)
{
string lang = string.Empty;//default to the invariant culture
HttpCookie cookie = Request.Cookies["pref"];
if (cookie != null && cookie.Value != null && !string.IsNullOrEmpty(cookie.Value.Trim()))
lang = cookie.Value;
if (string.IsNullOrEmpty(lang))
lang = "en-US";
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}
This time if I check the browser cookie it is rightly set to "fr-FR". But after this, when I go to home page and refresh this page cookie gets set to blank.
I'm not sure where it is getting overwritten. Any help?
I suppose that ddChoice_SelectedIndexChanged event is generated with empty SelectedValue and therefore your cookie is empty. Try to put breakpoint in the mehod or comment it out.
As your test case in the step 4 when you hit F5 page getting postback and language dropdown of language gets set with the default top language.
For that you need to write a function in control or page where your language dropdown is placed which set the selected lanaguage.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
setLangDropdown();
}
}
private void setLangDropdown()
{
HttpCookie cookie = Request.Cookies["pref"];
string lang = string.Empty;
if (cookie != null && cookie.Value != null && !string.IsNullOrEmpty(cookie.Value.Trim()))
lang = cookie.Value;
if (!string.IsNullOrEmpty(lang))
ddChoice.SelectedValue = lang;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("pref");
cookie.Value = ddChoice.SelectedValue;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(ddChoice.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(ddChoice.SelectedValue);
}

Resources