C# overwrite Existing Cookie in CookieContainer? - c#

I request a page with HTTPWebRequest and using this code. I add cookie
agent.cookieJar.Add(new Uri("http://www.website.com"),
new Cookie("brbr", "harta&brbra&=-"));
I ended up with two of the same cookies with different values in each of them. Because the
request has Javascript cookies sent back. What function should I use to
overwrite/update "brbr" cookie When I need to?

Their is overwrite method available in C# HttpCookie clas but you can overwrite the value of the cookie as you want as shown below
Request.Cookies["brbr"] = "Some New Value";
Or
Response.Cookies["brbr"] = "Some New Value";

Kind of an old question, but figured I would post anyway. The Set method on your cookie collection should do the job.
agent.cookieJar.Set(new HttpCookie("brbr", "harta&brbra&=-"));
This way you don't have to worry if the cookie already exists or not.

Related

C# - HttpClient is not sending any cookies

I am developing two websites names www.web1.com and www.web2.com.
In web1 I am saving a http cookie as below
HttpCookie AuthCookie = new HttpCookie(AppConstants.Cookie.AUTH_COOKIE);
AuthCookie.Path = "/";
AuthCookie.Value = "value1";
Response.Cookies.Add(AuthCookie);
Now what I want is to read this cookie in the second website i.e. web2. I am trying to read it using HttpClient as below
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = new CookieContainer();
HttpClient client = new HttpClient(handler);
response = client.GetAsync("http://www.web1.com").Result;
var cookies = cookies.GetCookies(new Uri("http://www.web1.com"));
This doesn't returns any cookies, checked via Fiddler as well. But if I directly open the www.web1.com and check fiddler then it sends the cookie.
Please see what I am missing so that the cookie is not returned from httpclient.
Thanks,
SB
Not sure if this would work properly in your case but AuthCookie.Domain = "IP/Domain"; should do the job for you.
Having said that there are other alternatives like query string and page post on other domain that might interest you.
You can't get or set cookies for another domain. That would be a huge security issue. (would you want me reading your site's cookies on my site?)
Some related posts:
Create a asp.net authenicated cookie on 1 site for another
I need to get all the cookies from the browser
Create cookie with cross domain
Cross domain cookies
UPDATE: A bit of clarification: As a server, you can't get or set cookies on a client for another domain, which is what you want to do. As a client, you can modify / delete cookies that a server sets for you.
In your example, your server-side code is making the request to web1.com. You are not going to get a cookie for a random client. The client isn't involved at all in your code above.
If I visit web1.com and you set a cookie called "username" with a value of "bob", I can, as a client, modify this cookie to have a value of "admin" and then potentially have admin rights to your site, depending on how you are handling your cookies.

C# Cookies (problem with modifying/replacing)

I cannot modify last value of SessionKey which stored in cookies from server side. SessionKey in next request is still has old value. What wrong in my server's side code?
var varHttpListenerContextResponseCookie_SessionKey =
refHttpListenerContext.Response.Cookies[Constants.Cookies.LongNames.SessionKey];
if (varHttpListenerContextResponseCookie_SessionKey != null)
{
varHttpListenerContextResponseCookie_SessionKey.Value = refSessionKey;
}
else
{
refHttpListenerContext.Response.AppendCookie(
new System.Net.Cookie(Constants.Cookies.LongNames.SessionKey, refSessionKey));
}
Please help me!:)
You must remember to add your modified cookie to Response if you want to update value
// get existing cookie or create new
var cookie = Request.Cookies[Constants.Cookies.LongNames.SessionKey] ?? new HttpCookie(Constants.Cookies.LongNames.SessionKey);
// set cookie value
cookie.Value = refSessionKey;
// add cookie to http repsonse
Response.Cookies.Add(cookie);
MSDN - Basics of Cookies in ASP.NET
From my understanding you want to modify your session Key. If it is right then you can make use of SessionManager, which will let you create a new session key. If this is not what you wanted please give more details about your question.
Thanks,
Shashi
If your question is answered kindly mark it as Answered.
Also when modifying/adding a cookie, don't forget to create/increase the expiration, as expired cookies may not be retrievable
cookieForPage.Expires = DateTime.Today.AddYears(100);

Create new cookie to edit its value

I know that you can't edit incoming cookies. I have a cookie that I just need to read..nothing more but I have a need to remove some characters from its value so that I can parse it. How can I do this? I don't need to send the modified new cookie back in the response, it's just for my server-side consumption and then that's it.
Updated:
figured it out:
HttpCookie facebookAuthCookie = HttpContext.Current.Request.Cookies[facebookCookieName];
string cleanValue = facebookAuthCookie.Value.Replace("\"", string.Empty);
HttpCookie cleanedFacebookAuthCookie = new HttpCookie("cleanedFacebookCookie", cleanValue);
gayness
Is it too simple to say read the values into a local variable and do whatever you want there?

How to read cookie that written in login method?

If the login code int
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket(v=VS.90).aspx
we will found that they create cookie as below
new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
I want in another code to read this cookie and check it .. how can i do although i don't know the name of the cookie ?
you can change the name of the forms authentication cookie in the web.config for your ASP.NET application.
your code doesn't need to know the exact cookie name. You can use the FormsAuthentication.FormsCookieName property instead.
You have the answer in your example, the cookie is named by the value contained in:
FormsAuthentication.FormsCookieName

Cookie loses value in ASP.net

I have the following code that sets a cookie:
string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue;
HttpCookie cookie = new HttpCookie("localization",locale);
cookie.Expires= DateTime.Now.AddYears(1);
Response.Cookies.Set(cookie);
However, when I try to read the cookie, the Value is Null. The cookie exists. I never get past the following if check:
if (Request.Cookies["localization"] != null && !string.IsNullOrEmpty(Request.Cookies["localization"].Value))
Help?
The check is done after a post back? If so you should read the cookie from the Request collection instead.
The cookies are persisted to the browser by adding them to Response.Cookies and are read back from Request.Cookies.
The cookies added to Response can be read only if the page is on the same request.
The most likely answer is seen on this post
When you try to check existence of a cookie using Response object rather than Reqest, ASP.net automatically creates a cookie.
Edit: As a note, I ended up writing software that needed to check the existence of cookies that ASP.NET makes a nightmare due to their cookie API. I ended up writing a conversion process that takes cookies from the request and makes my state object. At the end of the request I then translate my state object back to cookies and stuff them in the response (if needed). This alleviated trying to figure out if cookies are in the response, to update them instead, avoiding creating of pointless cookies etc.
Have you tired "Request" collection instead of "Response" collection?
if (Request.Cookies["localization"] != null && !string.IsNullOrEmpty(Request.Cookies["localization"].Value))
I had a similar problem, I couldn't read cookies on postback. The issue for me was that I checked the Secure property of the cookie to true. It is said that when the Secure property of the cookie is turned on, it causes the cookie to be transmitted only if the connection uses the Secure Sockets Layer. I am not sure, however, how I was able to see the cookie in the browser the first time, but not on postback, considering that I wasn't transmitting over SSL. Anyhow, turning the cookie.Secure to false, solved the problem, and had cookies read on postback.
Sorry if this doesn't have to do anything with your issue, I wanted to share this, because I spent some time looking how to resolve this.
I think I know the answer.
Just REMOVE the action attribute in your <form> tag.
make it look like this: <form id="form1" runat="server">
instead of this: <form id="form1" action="DisplayName.aspx" runat="server">
You should then use Response.Redirect("DisplayName.aspx"); in your code.
if you're compiling in debug mode, turn on tracing for the pages in question and make sure the cookie is in the request collection. Set trace in the #page directive in the aspx file.
Try this snippet -
string locale = ((DropDownList)this.LoginUser.FindControl("locale"))
.SelectedValue;
HttpCookie myCookie = new HttpCookie("localization");
Response.Cookies.Add(myCookie);
myCookie.Values.Add("locale", locale);
Response.Cookies["localization"].Expires = DateTime.Now.AddYears(1);
& to read it -
if (Request.Cookies["localization"] != null)
{
HttpCookie cookie = Request.Cookies["localization"];
string locale = cookie.Values["locale"].ToString();
}
Would add this as a comment to Chris Marisic's answer but I don't have that privelage :-(
Further to what Chris said in his edit about removing cookies from the request, to be able to read the newly created cookies value in a postback I ended up doing
Private Sub SetPageSize(ByVal pageSize As Integer)
' Set cookie value to pageSize
Dim pageSizeCookie As HttpCookie = New HttpCookie(pageSizeCookieName)
With pageSizeCookie
.Expires = Now.AddYears(100)
.Value = pageSize.ToString
End With
' Add to response to save it
Me.Response.Cookies.Add(pageSizeCookie)
' Add to request so available for postback
Me.Request.Cookies.Remove(pageSizeCookieName)
Me.Request.Cookies.Add(pageSizeCookie)
End Sub
The Request.Cookies.Remove and Request.Cookies.Add lines making it work on postbacks
use Response.Cookies.Add(cookie); instead of Response.Cookies.Set(cookie);

Categories

Resources