Read cookie value with c# - c#

using asp.net/c#, how is possible to :
display a webform only when the cookie value has been set to "1". (on page_load event)
So the asp code should just read the cookie value and make visible/invisible the webform
Note that the cookie value I will set it with php.
Note that the html webform is included in the code:
asp:Content ID="webform" ContentPlaceHolderID="webform1" runat="Server"
So I need a way to manipulate this webform depending of the settings of the cookie value that I will read all the time the page gets loaded

if (!Page.IsPostback)
Call the method below, based on the return value response.redirect to another page.
private string GetCookieValue(string cookieName, string itemName)
{
var CookieName = "MY_COOKIE";
var CookieValue = string.empty;
HttpCookie myCookie = Request.Cookies[CookieName];
if (myCookie == null) return "No cookie found";
//If you added a key vs. the value in the cookie use this code
//CookieValue = myCookie[itemName].ToString();
//Get the value of the cookie if you are not using a key
CookieValue = myCookie.Value.ToString();
Return CookieValue;
}

Related

Shopping Cart Cookie not working in c# MVC

What this cookie aims is (if the cookie exists) to remember CartId so that user anonymous or registered can see his cart. If cookie doesn't exists it creates one with GuId and stores the cartId for some period of time.
I tried in some way to achieve that in this code:
enter image description here
And here cookie isn't working. It saves only cookie in line 190 with CartId always 0 and the other if and else statements are not checked. The line 190 I wrote it because it was throwing null exception statement without this line.Also I think that a mistake that I made is that I didn't use Current context above of line 197.
I tried to use HttpContext.Current and it throws this error :
enter image description here
Help me out please if it can be fixed. Any other example or url of cookies c# shopping cart is accepted. Thank you in advance.
First attempt:
public string GetCartId(HttpContextBase context )
{
if (context.Request.Cookies["CartId"] == null) return "0";
string cartId = context.Request.Cookies["CartId"].Value;
{
// if the cart ID doesn't exist in the cookie, generate
// a new ID
if (context.Request.Cookies["CartId"] == null)
{
// generate a new GUID
cartId = Guid.NewGuid().ToString();
// create the cookie object and set its value
HttpCookie cookie = new HttpCookie("CartId", cartId);
// set the cookie's expiration date
cookie.Expires = DateTime.Now.AddMinutes(2);
// set the cookie on the client's browser
context.Response.Cookies.Add(cookie);
// return the CartID
return cartId.ToString();
}
else // check if the cart ID exists as a cookie
{
// return the id
return cartId;
}
}
}
Here it saves cartId always null and not checking other statements
Second Attempt I added Current Context :
if (context.Request.Cookies["CartId"] == null)
{
HttpContext context = HttpContext.Current;
And context underlined with red says a local parameter named context cannot be declared in this scope because the name is used in an enclosing local scope.
Creating a cookies within a MVC Controller:
HttpCookie cookie = new HttpCookie("Cookie");
cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
Check & Read a cookie within a MVC Controller:
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
...
The Cookies.AllKeys.Contains() can replace your null check.
How to you call your method? What is the value of context?
The MSDN Documentation about Cookies can be found here...
Working with cookie in Legacy Asp.net was good, As you are developing application using MVC design pattern, Here we have other important concept to manage state.
Few are listed below:-
tempdata
viewdata
viewbag
And you can get explanation here
The value for the HttpOnly property of HttpCookie is "false" by default
This means you ask the browser to store your cookie on the disk
Change this to "true" before adding the cookie to the response. A note here, the client cookie will be lost if he closes all the instances of the browser.
If this does not help, you should add a privacy policy to your web site
try this, and if http only does not help, we can go for the p3p privacy policy solution

C# persistent cookie

I have seen the persistent cookies examples in ASP.NET MVC C# here on stackoverflow.
But I can't figure out why the code below isn't working.
First I write to the cookie:
HttpCookie cookie = new HttpCookie("AdminPrintModule");
cookie.Expires = DateTime.Now.AddMonths(36);
cookie.Values.Add("PrinterSetting1", Request.QueryString["Printer1"]);
cookie.Values.Add("PrinterSetting2", Request.QueryString["Printer2"]);
cookie.Values.Add("PrinterSetting3", Request.QueryString["Printer3"]);
Response.Cookies.Add(cookie);
I see the cookies stored in Internet Explorer. The content looks OK.
Then the reading code:
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie.Values["PrinterSetting2"].ToString();
The cookie variable keeps null . Storing the PrinterSetting2 value in the test variable fails.
I don't know what I'm doing wrong because this is more or less a copy-paste from the examples here on stackoverflow. Why can't I read the PrinterSetting2 value from the cookie ?
try with below code :-
if (Request.Cookies["AdminPrintModule"] != null)
{
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie["PrinterSetting2"].ToString();
}
Have a look at this document http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ :-
Below are few types to write and read cookies :-
Non-Persist Cookie - A cookie has expired time Which is called as
Non-Persist Cookie
How to create a cookie? Its really easy to create a cookie in the
Asp.Net with help of Response object or HttpCookie
Example 1:
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
Example 2:
Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";
How to retrieve from cookie?
Its easy way to retrieve cookie value form cookes by help of Request
object. Example 1:
string User_Name = string.Empty;
string User_Color = string.Empty;
User_Name = Request.Cookies["userName"].Value;
User_Color = Request.Cookies["userColor"].Value;
Example 2:
string User_name = string.Empty;
string User_color = string.Empty;
HttpCookie reqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}
You must ensure that you have values in Request.QueryString.Just to check if your code works hard code values of cookies and then read from cookie.

Localhost cookie in ASP.NET C#

I am trying to write cookie in ASP.NET using C# with this simple code:
HttpCookie cookie = new HttpCookie("UserToken");
cookie.Value = userToken.access_token; //string
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Cookie was build. I am using Chrome browser but the value (Konten) always empty. What's the problem?
I also try to read this cookie with this code:
if (Request.Cookies["UserToken"] != null)
string userToken = Request.Cookies["UserToken"].Value;
"UserToken" cookie is not null but the value was empty string.
Thanks in advance

How to request client cookies on server ASP.NET

I have a javascript function that updates a cookie in the following manner:
aspx page:
function setCookie()
{
//...
document.cookie = "myCookie = HelloWorld";
//...
}
After an asp control triggers an event, the entire page gets sent back from the client. I want to be able to read the value of my cookie. How do I do that?
I've tried:
string temp = Request.ServerVariables["myCookie"].ToString(); but that is the wrong way to do it.
How do I read the client cookie on the server
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
Source MSDN
Here is the helper method to retrieve cookie at server side.
public static String GetCookie(String cookieName)
{
try
{
if (HttpContext.Current.Request.Cookies[cookieName] == null)
return String.Empty;
return HttpContext.Current.Request.Cookies[cookieName].Value;
}
catch
{
return String.Empty;
}
}
Usage
var result = GetCookie("myCookie");
If you want to set cookie at client side, look at this Cookie plugin.

Do I have to rewrite cookie everytime I postback to retain it?

I don't really understand the difference between request cookie and response cookie. And it seem like everytime I postback, if I don't manually rewrite the cookie from request to response, then it disappears. How do I solve this?
public string getCookie(string name) {
if (Request.Cookies["MyApp"] != null && Request.Cookies["MyApp"][name] != null) {
return Request.Cookies["MyApp"][name];
} else if (Response.Cookies["MyApp"] != null && Response.Cookies["MyApp"][name] != null) {
return Response.Cookies["MyApp"][name];
} else {
return "";
}
}
public void writeCookie(string name, string value) {
Response.Cookies["MyApp"][name] = value;
HttpCookie newCookie = new HttpCookie(name, value);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
}
Request.Cookies["MyApp"];
Code above will return you a cookie with name "MyApp" Doing this:
Request.Cookies["MyApp"][name]
You are taking value "name" from cookie called "MyApp".
But in your setCookie code you are setting a cookie with called name and do not create a cookie called "MyApp":
HttpCookie newCookie = new HttpCookie(name, value);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
So, you should remove ["MyApp"] from any place you have it, or you may do something like this in setCookie:
public void writeCookie(string name, string value) {
if(Response.Cookies["MyApp"] == null) {
HttpCookie newCookie = new HttpCookie("MyApp");
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
}
if(Response.Cookies["MyApp"][name] == null)
Response.Cookies["MyApp"].Values.Add(name, value);
else
Response.Cookies["MyApp"][name] = val;
// or maybe simple Response.Cookies["MyApp"][name] = val; will work fine, not sure here
}
Request is the "thing" you get when the user tries to get to your website, while Response is a way of responding to this request.
In other words, see the official msdn documentation, namely this part:
ASP.NET includes two intrinsic cookie collections. The collection
accessed through the Cookies collection of HttpRequest contains
cookies transmitted by the client to the server in the Cookie header.
The collection accessed through the Cookies collection of HttpResponse
contains new cookies created on the server and transmitted to the
client in the Set-Cookie header.
http://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies.aspx
So no, you don't have to create new cookies every time, unless they have already expired. Just be sure you reference the right collection of cookies.
You might want to check the domain and path that are being assigned to the cookie. It could be that your saved cookies are just being orphaned because the path is too specific or because the wrong domain is being set.
Domain is the server name that the browser sees such as "yourdomain.com". If the cookie is set with a different domain than this then the browser will never send it back. Likewise, the path of the cookie is the path to the resource being requested such as "/forum/admin/index" etc. The cookie is sent for that location and all child locations, but not for parent locations. A cookie set for "/forum/admin/index" will not be sent if you're accessing a page that sits in the "/forum" directory.

Categories