Set and Get the Cookies in ASP.NET web forms - asp.net

The cookies in Asp.net are killing me! This is my Code:
set the cookie:(Upload is an asp:FileUpload control for uploading image)
HttpCookie cookie = new HttpCookie("WorkingImage", Upload.FileName.ToString());
cookie.Expires = DateTime.Now.AddDays(3);
HttpContext.Current.Response.Cookies.Add(cookie);
and this is the way I get it:
if (HttpContext.Current.Request.Cookies["WorkingImage"] != null && HttpContext.Current.Request.Cookies["WorkingImage"].Value.ToString() != "")
{ //....}
cookie value is "" when I run the project .
Is there any help?(please note that in other pages cookies can set and will got correctly)

Here is an example where we save a WorkingImage name in cookie
HttpCookie cookie = new HttpCookie("WorkingImage");
cookie.Value = Upload.FileName.ToString(); // Upload is an asp:FileUpload control name for uploading image
cookie.Expires = DateTime.Now.AddHours(3);
Response.SetCookie(cookie);
Here is example for accessing our cookie and check for the cookie :
if(Request.Cookies["WorkingImage"] != null)
{
var cookieValue=Request.Cookies["WorkingImage"].Value;
}

If you are using within handler inherit:
System.Web.SessionState.IRequiresSessionState
Like this:
public class Handler : IHttpAsyncHandler, System.Web.SessionState.IRequiresSessionState
For more cookies tutorials in asp .net visit this.

Related

Something wrong with cookies in asp.net

I am building a web application and when a user signs in, his credentials are first validated against the database. If the credentials are correct, a FormsAuthenticationTicket is created. Then a cookie is created from that ticket. The Expires and Path properties are set. See below.
FormsAuthenticationTicket ticket=new FormsAuthenticationTicket(1, model.User.UserName,
DateTime.Now, DateTime.Now.AddHours(2), RememberMeCheckBox.Checked,
model.User.Id.ToString()+" "+model.User.UserType.ToString());
string cookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
cookie.Expires=ticket.Expiration;
cookie.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(cookie);
Response.Redirect("DummyForm.aspx");
And when I redirect the response to a new page, in the Page_Load event the presence of a cookie is checked.
HttpCookie cookie=HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookiePath];
if(cookie!=null)
{
//Do stuff
}
else
{
//Do other stuff
}
When I run the application, it behaves like the cookie variable is null.
Is there something that I have omitted?
Thanks in advance for your help.
cookie.Domain="localhost";
cookie.Name="My auth cookie";
I also set the domain property to localhost in web.config. However, it still doesn't work. I used the developer tools of Google to check the cookie and I can't see it there.

LoginView Not Updating After User Login

I'm using ASP.NET Membership in order to manage a website users. But without using the specific 'Login Controls'. Actually, just applying Membership class methods in order to Create a user account and also to User login.
On the other hand, there is a LoginView control in Site.Master which is responsible to 'Welcome Username' task.
The problem is that, the LoginView control isn't updated after creating new account or any login.
Do I have to Definitely use the specific login controls?
----Also, I have set the Login Button CommandName to 'Login'!
----Should I set something like that for Create User Button?
I would appreciate any help...
The following is my code for login:
if (!Membership.ValidateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text)))
{
lblResult.Text = "Invalid user name and password.";
lblResult.Visible = true;
}
else
{
Response.Redirect("~/Default.aspx");
}
And here the registration code:
MembershipCreateStatus statusUser;
try
{
Membership.CreateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text), HttpUtility.HtmlEncode(txtEmail.Text), ddlSexQues.SelectedValue != "-1" ? ddlSexQues.Text : string.Empty, txtSecAnsw.Text == string.Empty ? string.Empty : txtSecAnsw.Text, true, out statusUser);
txtEmail.Text = string.Empty;
txtPass.Text = string.Empty;
txtRepass.Text = string.Empty;
txtSecAnsw.Text = string.Empty;
txtUserName.Text = string.Empty;
ddlSexQues.SelectedValue = "-1";
lblRsl.ForeColor = Color.Green;
lblRsl.Text = "حساب کاربری شما با موفقیت ایجاد شد.";
lblRsl.Visible = true;
}
catch (MembershipCreateUserException error)
{
lblRsl.Text = GetErrorMessage(error.StatusCode);
lblRsl.Visible = true;
}
If you're using your own login code, you'll need to persist the user's authentication information, for instance by adding a cookie to the response. The built-in controls do this automatically.
I'm assuming you're using Forms-based authentication. There's a reference to the .NET security class for Forms auth here, which details what options are available to you:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx
Look at the SetAuthCookie and RedirectFromLoginPage methods in particular.
As far as I'm aware, the CommandName property is for distinguishing between Button controls in code. As you're using your own methods to handle user creation, I don't think you need to add it to your own control. More here:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx

Asp.Net 4 Response.Cookies.Add does not add cookie to users machine

I am trying to setup a basic Form Authentication using ASP.NET 4.
I know my validation code (code that checks if the username and password is correct) is working because after if the user enters invalid information the ReturnLable tells them so. However if they enter the correct information, they are redirected to the restricted page with a 403 – Forbidden error. When I check the shell:cookie path no cookie has been written even though I added it to the collection “Response.Cookies.Add(cookie);”
protected void Submit_Click(object sender, EventArgs e)
{
Email.Text = Email.Text.Trim();
Password.Text = Password.Text.Trim();
if (IsValid(Email.Text, Password.Text)) //user exists
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
Email.Text,
DateTime.Now,
DateTime.Now.AddMinutes(50),
RememberMe.Checked,
"user",
FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
}
else
{
ReturnLable.Text = "<font color=red> Username/Password Incorrect Please Try Again </font>";
ReturnLable.Visible = true;
}
From this MSDN article:
If you do not set the cookie's expiration, the cookie is created but
it is not stored on the user's hard disk. Instead, the cookie is
maintained as part of the user's session information. When the user
closes the browser or if the session times out, the cookie is
discarded.
Thus, a cookie could be successfully set, alive and well in the browser, but have no corresponding file in the "cookies" folder on the hard drive.
make sure that Enable anonymous access is disabled on IIS and Integrated Windows security is enabled

How can I delete a cookie in a particular page?

I am creating a cookie in one page of an ASP.NET application and I want to delete it in another page. How do I do that?
Microsoft: How To Delete a Cookie
You cannot directly delete a cookie on a user's computer. However, you can direct the user's browser to delete the cookie by setting the cookie's expiration date to a past date. The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
To assign a past expiration date on a cookie
Determine whether the cookie exists in the request, and if so, create a new cookie with the same name.
Set the cookie's expiration date to a time in the past.
Add the cookie to the Cookies collection object of the Response.
The following code example shows how to set a past expiration date on a cookie.
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Note: Calling the Remove method of the Cookies collection removes the cookie from the collection on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.
Have you tried expiring your cookie?
protected void btnDelete_Click(object sender, EventArgs e)
{
Response.Cookies["cookie_name"].Expires = DateTime.Now.AddDays(-1);
}
How to: Delete a Cookie
if (Request.Cookies["MyCookie"] != null)
{
HttpCookie myCookie = new HttpCookie("MyCookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
First you have to set the expiry date of the cookie to a previous date.
For Example :
HttpCookie newCookie = new HttpCookie("newCookie");
newCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(newCookie);
Now only doing this will not be helpful as the cookie will not be physically removed. You have to remove the cookie.
if (newCookie.Expires < DateTime.Now)
{
Request.Cookies.Remove("newCookie");
}
Here you go. This applies to any page within the solution.

Login Control - Response.Redirect

I have a usercontrol on a page that has a login control in it. This controls the display of another user control (if the user is not logged in they get the login control user control). I have some authentication code (see below) that runs when the user clicks the "Login" button. Basically I want it to post back to the same page so they will be logged in and able to now see the other protected user control. This code is not working. Perhaps there is something going on in another page that is making this not work, but does this code itself seem like it should work?
string userName = Membership.GetUserNameByEmail(Login1.UserName);
if (userName != null)
{
e.Authenticated = Membership.ValidateUser(userName, Login1.Password);
}
else
{
e.Authenticated = false;
}
if (e.Authenticated)
{
Login1.UserName = userName;
ImageButton loginButton = (ImageButton)Login1.FindControl("LoginButton");
if (loginButton != null)
{
//loginButton.PostBackUrl = Request.Url.ToString();
Response.Redirect(Request.Url.ToString());
}
}
The issue is the login control will itself do a redirect setting a cookie or an encrypted authentication ticket in the url (cookieless).
I think the login control has some properties where you can tell it where it will be redirecting to (which overrides the one in the web.config).
DestinationPageUrl is the property... soo Login1.DestinationPageUrl = "~/whatever.aspx";

Resources