Cookies in ASP.NET - asp.net

I'm looking for a good example of storing data in a cookie using ASP.NET. Could someone show me an example?

MSDN is quite your friend : http://msdn.microsoft.com/en-us/library/78c837bd.aspx
Until then :
C#:
Response.Cookie["cookie_name"] = "value";
VB:
Response.Cookie("cookie_name") = "value";

How to Create a cookie
HttpCookie mycookie = new HttpCookie("mycookie");
mycookie.Value = "chocolate chip please.";
Response.Cookies.Add(mycookie);
How to Read a cookie
HttpCookie mycookie = Request.Cookies["mycookie"];
Response.Write("Your cookie is: " + mycookie.Value);

check this out
Save Form Data With Cookies

Google says "How to Write a Cookie"

Related

Can I save data/value in browser session storage using asp.net

However, i can save and retrieve data to browser from clientside. I'm not sure, but is there any way I could do it from serverside. Thanks in advance for any solution and advices.
I think I have the solution. Below is the code I found, which helped me to expose data from server-side to the client side.
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "sessionStorage.setItem('Username','Something')", true);
For Creating Session
Session["Username"] = " Mairaj";
To Get Value from Session
string userName = string.Empty;
if(Session["Username"] != null)
userName= Session["Username"].ToString();
To get value from Session in aspx page.
var userName = '<% =Session["userName"]%>';
You can get value from Session in aspx page not in external JS file.

Set and Get the Cookies in ASP.NET web forms

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.

How to redirect to home page of Pentaho after basic authentication in .NET?

I try to use basic authentication in VB.NET side to login Pentaho
I use the default account of Pentaho for testing
username: joe
password: password
I have following code in VB.NET for basic authentication to Pentaho
Dim request = WebRequest.Create("http://x.x.x.x:8080/pentaho/Home")
Dim authInfo As String = Convert.ToString(userName) & ":" & Convert.ToString(userPassword)
authInfo = Convert.ToBase64String(Encoding.[Default].GetBytes(authInfo))
request.Headers("Authorization") = "Basic " & authInfo
Dim response As WebResponse = request.GetResponse()
After ran the request.GetResponse() can get the successful result. So I think the Pentaho login and authentication successfully
But when I go to http://x.x.x.x:8080/pentaho/Home Pentaho still prompt to Login Pageā€¦
Do You know What wrong of my code?
Thanks in advance!!
Not sure what you're trying to do here. Where are you going to pentaho/Home. In your code ?
If you want to programatically call a certain URL in Pentaho, it's probably easier to append the credentials to the query string.
You can use Basic Authentication method, I already answered this question in bellow post.
enter link description here
Eg-
WebClient webClient = new System.Net.WebClient();
Uri uri = new Uri("http://serverDomain:8080/pentaho/Home");
//Give user name and password here
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("username:password");
var encodedString = System.Convert.ToBase64String(plainTextBytes);
webClient.Headers["Authorization"] = "Basic " + encodedString;
webClient.Encoding = Encoding.UTF8;
App.WindowManager.ConsoleWrite(uri.ToString());
webClient.UploadStringAsync(uri, "POST", "");

asp.net delete cookie

I'm using a cookie containing an encrypted key to use for authentication. What i need is to delete this cookie on logout. As per msdn a cookie cannot be removed from a client's browser, so I tried to set expiry date HttpContext.Current.Request.Cookies["CAuthCookie"].Expires = DateTime.Now.AddDays(-1);, however the cookie remains. Any other ideas?
Try this:(place this in your logout code)
HttpCookie cookie = new HttpCookie("CAuthCookie", "");
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Set(cookie);

FormsAuthentication isn't preserving the UserData field after Postback in .NET 3.5

I've created a FormsAuthenticationTicket from scratch, but found that when retrieving it at a later time, the UserData isn't coming back. Here is the code used:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
user.UserId,
DateTime.Now,
DateTime.MaxValue,
false,
user.UserType);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
However, when reading this back on the next Request, I found that the UserData field is now empty:
string encryptedCookie = Request.Cookies[ FormsAuthentication.FormsCookieName ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsTrue( ticket.UserData.Length == 0 ); //TRUE!
Any ideas?
I think I found the problem. If you make up your own cookie name it seems to be fine! So change from:
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
to
HttpCookie cookie = new HttpCookie(
"SiteCookie",
FormsAuthentication.Encrypt(ticket));
And then retrieve it as per the question:
string encryptedCookie = Request.Cookies[ "SiteCookie" ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsFalse( ticket.UserData.Length == 0 ); //Hooray! It works
Its possible .NET does some tricky stuff with it, so by putting it in a new one works fine.
UPDATE:
Also, the ticket needs to be refreshed, as otherwise the ticket will expire while the user is using the website:
FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie
I have also encountered this problem.
But I think the real reason is that the server set the same cookie twice and the second override the first which contains your UserData field.
You can capture the cookie writing process by Fiddler, and here is a screenshot that show this problem:
So, how this happened? In my situation, I use the Login control to authenticate. In the Login control's Authenticate event, I set the cookie with my UserData after check the username and password manaully. Then, I set the AuthenticateEventArgs.Authenticated=true, at this time, in the debug window, I see a new cookie is queued to the response which name is also equal to FormsAuthentication.FormsCookieName ! My solution is redirect to the Default page instead of setting the AuthenticateEventArgs.Authenticated=true.
So, you may debug your code to see if the authentication cookie is queued to the response twice.
This works for me:
//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, currentUser.userid.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, currentUser.ToString(), FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);

Resources