I have a code as follows:
this.Response.Cookies.Add(new HttpCookie("COOKIENAME",'test'));
I want to add the domain ".test.com" for this cookie. How do I do so? I tried the standard:
this.Response.Cookies["COOKIENAME"].Domain = ".test.co.uk";
But the cookie is not being set for the whole domain. Any suggestions?
The following is not working either:
HttpCookie MyCookie = new HttpCookie("COOKIENAME");
MyCookie.Value = 'test';
MyCookie.Domain = ".test.co.uk";
this.Response.Cookies.Add(MyCookie);
I don't think you need the ".", so just MyCookie.Domain = "test.co.uk";.
I think you should use the Cookie Path property to define the domain of the cookie
Related
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.
I am using cookies for my website.
I need to remove cookies immediately from browser for that i use this Code in C#
Code for removal of cookie
Response.Cookies["OptDepth"].Expires = DateTime.Now.AddYears(-30);
after execution of this code if i use this code
Code to check value of deleted cookie
Request.Cookies["OptDepth"].value;
then it gives me the value of specified cookie.
I need to remove cookies immediately from browser.
How can i do this.
If we change the name of that cookie with null then it works.
Code
Request.Cookies["OptDepth"].Name = null;
Now problem is solved.
Use Simple Code to replace cookies with expiry date:
if (Request.Cookies["OptDepth"] != null)
{
HttpCookie myCookie = new HttpCookie("OptDepth");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Here is an msdn detail link.Cookies
When adding a cookie ;
HttpCookie cookie = new HttpCookie("try");
cookie.Values["foo"] = "foo";
DateTime date = DateTime.Now.AddSeconds(-30);
cookie.Expires = date;
Response.Cookies.Add(cookie);
When Reading the cookie;
HttpCookie cookie = Request.Cookies["try"];
You will see the cookie is null.
I am building dnn module which allow logged in user to log in as another user.
But I have some wired issue here.
This is how I log out current user and login as another user:
UserInfo userInfo = UserController.GetUserById(portalId, userId);
if (userInfo != null)
{
DataCache.ClearUserCache(this.PortalSettings.PortalId, Context.User.Identity.Name);
if (Session["super_userId"] == null)
{
Session["super_userId"] = this.UserId;
Session["super_username"] = this.UserInfo.Username;
}
HttpCookie impersonatorCookie = new HttpCookie("cookieName");
impersonatorCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(impersonatorCookie);
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
PortalSecurity objPortalSecurity = new PortalSecurity();
objPortalSecurity.SignOut();
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
Response.Redirect(Request.RawUrl, true);
}
And in PageLoad() I try to read value from this cookie but it doesn't read anything:
try
{
string super_userId = Request.Cookies["cookieName"]["super_userId"];
string super_username = Request.Cookies["cookieName"]["super_username"];
if (!String.IsNullOrEmpty(super_userId))
{
this.Visible = true;
this.lblSuperUsername.Text = Session["super_username"].ToString();
this.txtPassword.Enabled = true;
this.btnBackToMyAccount.Enabled = true;
}
...
I also have tried to do the same with session but nothing works, and I can't figure why?
As I find here, there can be problems with setting cookies in a request that gets redirected, and here is stated that cookies won't get set with a redirect when their domain is not /.
So you can try to not redirect using HTTP headers, but show a "Logged In" page instead that contains a "Home" link and a meta refresh or Javascript redirect.
By the way, setting a UserID in a cookie is not really the way to go. What if I change that cookie value to 1?
I suggest when you set a new cookie to always set the Domain, and probably and the Expires.
Response.Cookies[cookieName].Domain = RootURL;
Response.Cookies[cookieName].Expires = DateTime.UtcNow.AddDays(cDaysToKeep);
The domain is very importan to be the url with out the subdomain, eg only the mydomain.com with out the www. because if a cookie is set from www.mydomain.com and you try to read it from mydomain.com or vice versa, then the cookie will not be read and you may lost it / overwrite it.
So I suggest to make a function that when you set a cookie, you set at least 3 parametres, the Domain, the Expires, and the Value.
Similar questions and answers :
Multiple applications using same login database logging each other out
asp.net forms authentication logged out when logged into another instance
Put these two statements
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
after
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
May be the UserLogin method is resetting the Session variables.
Hope it Helps :)
I have a problem with creating HttpOnly Cookies , I use the following code to creat new cookie:
//A.aspx
HttpCookie ht = new HttpCookie("www");
ht.Value = "www";
ht.Name = "www";
ht.HttpOnly = true;
ht.Expires = DateTime.Now.AddDays(1);
Response.AppendCookie(ht);
Response.Redirect("B.aspx");
//B.aspx
HttpCookie cookie = Request.Cookies["Allowed"];
HttpCookie htt = Request.Cookies["www"];
if (cookie != null)
{
Response.Write(cookie.HttpOnly);
Response.Write(htt.HttpOnly);
}
else
{
cookie = new HttpCookie("Allowed");
cookie.HttpOnly = true;
cookie.Value = "ping";
cookie.Expires = DateTime.Now.AddMinutes(2);
Response.Cookies.Add(cookie);
Response.Write(cookie.HttpOnly);
Response.Write(htt.HttpOnly);
}
The problem is that the final result is always : False, although the HttpOnly property is set to True .
Can anyone explain me a way to figure this out ?
Thanx
Cookie parameters (expiration date, path, HttpOnly etc) are not sent back to the server by the browser, only the values. Sending them back would only introduce unnecessary bloat. Therefore the cookies in Request.Cookies will only contain the names and values.
If you want to see if your HttpOnly value is taking effect, use Firecookie or something similar to inspect the cookies. Or try accessing them in JavaScript - that's what it's supposed to prevent.
So I'm confused as msdn and other tutorials tell me to use HttpCookies to add cookies via Response.Cookies.Add(cookie). But that's the problem. Response.Cookies.Add only accepts Cookies and not HttpCookies and I get this error:
cannot convert from 'System.Net.CookieContainer' to 'System.Net.Cookie'
Additionally, what's the difference between Response.Cookies.Add(cookie) and Request.CookieContainer.Add(cookie)?
Thanks for the help in advance, I'm trying to teach myself using C#.
// Cookie
Cookie MyCookie = new Cookie();
MyCookie.Name = "sid";
MyCookie.Value = SID;
MyCookie.HttpOnly = true;
MyCookie.Domain = ".domain.com";
// HttpCookie
HttpCookie MyCookie = new HttpCookie("sid");
MyCookie.Value = SID;
MyCookie.HttpOnly = true;
MyCookie.Domain = ".domain.com";
Response.Cookies.Add(MyCookie);
You are using System.Net.HttpWebResponse. But the above example uses System.Web.HttpResponse which takes System.Web.HttpCookie as a parameter.
Scott Allen
System.Web.HttpRequest is a class used
on the server and inside an ASP.NET
application. It represents the
incoming request from a client.
System.Net.HttpWebRequest is a class
used to make an outgoing request to
a web application.