I am using ASP.net to store cookies. I save a cookie on a popup in the code behind (C#). If I request the cookie, before the popup closes, then the cookie is there, however closing the popup and going back into it and looking at the cookie in the Page_Load event shows no cookie. How do I get it to persist?
Following code in popup OK button
// Set the cookie.
this.Response.Cookies["UserData"].Secure = true;
this.Response.Cookies["UserData"]["UserId"] = iId.ToString();
this.Response.Cookies["UserData"]["UserEmail"] = strEmail;
this.Response.Cookies["UserData"].Expires = DateTime.Now.AddDays(1);
Following code placed in Page_Load event
// Get the cookie.
if (null != this.Request.Cookies["UserData"])
{
// Transmit the cookie information using SSL. Note, the cookie data is still in plain text on the user's computer.
this.Request.Cookies["UserData"].Secure = true;
// Extract: Email
String strEmail = this.Server.HtmlEncode(oPage.Request.Cookies["UserData"]["UserEmail"]);
}
Naturally, the very first time will show nothingness, however subsequent loads should show the cookie.
I had slightly better luck with using .Values["Subitem"] = "whatever", but that yielded the base to persist, but all subitems to disappear.
One possible reason: your page is HTTP, but you are setting cookies to be HTTPS-only. So browser simply does not send them back with HTTP request to your site.
Use Fiddler (or other HTTP debugger) to see if cookie is correctly send in the response (and next request).
Related
I've found a few posts about retrieving HTML from an ASPX page, mostly by overriding the render method, using a WebClient, or creating an HttpWebRequest. All these methods return the HTML of the page as it's loaded, but I was hoping to actually retrieve the HTML after the user has entered information.
The purpose behind this is that I work in IT, and I'm attempting to build a logging library that has an overload that essentially does a "screen-scrape" on the page just as the user encounters an exception, that way I can log the exception, and create an HTML file in a sub-directory of the logging directory that shows the page exactly as the user had it before clicking "submit" or having some other random error, and add an "ID" to the error that's logged telling whoever is fixing the issue which page to look at.
I hope I've provided enough information, because I really have no idea where to start.
Also, We'd like to do this through our own library, because our logging library is included in our common library, and many of our common library functions use our logging class.
Hmmm...
If you want to see what the user sees after they've been using the page, you're most likely going to have to do some fancy client-side scripting.
A naive approach:
When the clicks the submit button, fire a JavaScript event that encodes the DOM and either passes it as a form variable to the server, or executes a separate AJAX request with the encoded data as a parameter. ("Encode" in this case may be as simple as grabbing document.innerHtml, but I haven't checked.)
This potentially introduces a lot of overhead to every form submission, so I'd keep it out of production code.
I'm not sure why you need the rendered HTML as part of your exception log - I've never found it necessary for server-side debugging.
You getting HTML code from a website. You can use code like this.
string urlAddress = "http://www.jobdoor.in";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
I want to redirect a response to another URL while it contains some POST data in it's HTTP header.
// Inside an ASP.NET page code behind:
Response.Redirect("http://www.example.com/?data=sent%20via%20GET");
// This will sent data to http://www.example.com via GET.
// I want to POST this data to http://www.example.com instead.
How to do this in ASP.NET?
you can send huge data also with this trick..
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.AppendFormat(#"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>",postbackUrl);
sb.AppendFormat("<input type='hidden' name='id' value='{0}'>", id);
// Other params go here
sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");
Response.Write(sb.ToString());
Response.End();
You can't POST using a redirect. By definition a redirect means the server sending a 302 redirect HTTP status code to the client with the new location so that the client issues a GET request to this new location. That's how the HTTP protocol works and there's not mu ch you can do about it.
So one way to achieve this would be to redirect to some temporary page that will contain an HTML <form> with method="POST" and containing the values you want to send as hidden fields. Then you could use javascript to autosubmit this form.
Though it is quite old thread, I thought I would share how I do it.
Let's say sending page is a.aspx and destination page is b.aspx.
Collect user inputs in a.aspx. User clicks submit button which causes postback.
inside Button_click event of a.aspx, process volume data (for example save uploaded binary files). Determine link of the volume data and append that to end of request.form name-value string.
Encrypt the final name-value string and set it to a cookie.
Redirect to b.aspx
in b.aspx, retrieve that cookie, decrypt and you get all name-value pair. Now process them as usual.
Advantages:
(a) b.aspx is shown in browser address bar. It enters in browser's history. Server.transfer do these.
(b) It gives effect of post. Users can not see the name-value pair in querystring.
You can use viewstate to "transfer" the data and read it on a new page or even the same page.
I have very large website which uses a lot of cookies. There are approx. 14 different cookies are there. I have different cookies for each item. When a user surfs the site they will have 14 cookies in their browser. I do not want this.
I want a single cookie for my site that will have 14 items and I can add,edit and delete them. I tried many ways but I am not able to do this.
I need to put some run time cookies as well save the user name in cookie. After the user logs in I want to save their personal site address in it. Eventually I want both the user name and personal site address both. I want to save user name before and then when user goes to his personal site then i will store personal site name run time.
Does any one have an idea how I could do this?
Matthew beat me to it, but yes, see the ASP.NET Cookies Overview...
To write and read a single cookie with multiple key/values, it would look something like this:
HttpCookie cookie = new HttpCookie("mybigcookie");
cookie.Values.Add("name", name);
cookie.Values.Add("address", address);
//get the values out
string name = Request.Cookies["mybigcookie"]["name"];
string address = Request.Cookies["mybigcookie"]["address"];
There is a section in the ASP.NET Cookies Overview that discusses how to implement multiple name-value pairs (called subkeys) in a single cookie. I think this is what you mean.
The example from that page, in C#:
Response.Cookies["userInfo"]["userName"] = "patrick"; //userInfo is the cookie, userName is the subkey
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); //now lastVisit is the subkey
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
EDIT: From the Cookies Overview (emphasis added):
Modifying and Deleting Cookies:
You
cannot directly modify a cookie.
Instead, changing a cookie consists of
creating a new cookie with new values
and then sending the cookie to the
browser to overwrite the old version
on the client.
Modifying and Deleting Cookies: You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.
The situation:
I have 2 webpages with 2 domains (backoffice.myurl.com & www.myurl.com).
The backoffice is written in classic asp, the frontend in asp.net 3.5 (vb.net)
When I hit a button in the backoffice, I want to set a cookie on the frontend.
I do this by calling a page on the frontend via Microsoft.XMLHTTP
Dim GetConnection
Set GetConnection = CreateObject("Microsoft.XMLHTTP")
GetConnection.Open "POST", webserviceLocation, False
GetConnection.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
GetConnection.Send("data=" &value)
In the aspx code I read the posted value and put it in a cookie:
If Not Request.Cookies("mytest3") Is Nothing Then
Response.Cookies("mytest3").Expires = Now.AddYears(-23)
End If
Response.Cookies.Set(New HttpCookie("mytest3", Request.Form.Item("data")))
Response.Cookies("mytest3").Expires = DateTime.Now.AddYears(30)
On another page on the frontend I want to read that cookie:
Request.Cookies("mytest3").Value
but the Request.Cookies("mytest3") is 'nothing' there.
Apparently the cookie is not set. What am I doing wrong or how can I solve this?
The pages are called (my debugger hits the breakpoints)
Is this even possible at all?
When creating the cookie you need to explicitly set the domain:
' I do not remember if the value should be set to myurl.com or .myurl.com
' Please test
Response.Cookies("mytest3").Domain = "myurl.com"
This way the browser will send the cookie along each request to *.myurl.com
Darin has answered your question but you have another problem with this line:-
Response.Cookies("mytest3").Expires = Now.AddYears(-23)
The response Cookie collection is a differentc collection to that of the Request collection. The response cookies is always empty until code specifically adds a cookie to it. Hence the above line will fail.
i need to check whether the user clicking the browser Refresh button and redirect to error page. Can we do this in javascript or any server side methods in ASP.net
If you give each link you present a unique ID (e.g. a GUID) in the URL as a parameter, then you can keep track of all the requests you've processed. (You could clear out "old" requests if you don't mind the mechanism not working if someone leaves a browser open for a few days and then hitting refresh.) The first time you see a GUID, write it into the table. If you see it again, redirect to an error page.
It's pretty ugly though, and users could just edit the URL to change the GUID slightly. (You could fix this last flaw by recording the GUID when you generate it, and update the table to indicate when it's been used.)
In general, users expect to be able to refresh the page though - particularly for GET requests (even though most users wouldn't know what that means). Why do you want to do this?
Well, you can use a very famous tecnique called "Syncronizing Token" or something like that =D, mostly used to send forms.
This will work like this:
Create a function to provide a pseudo-random string token.
For every request to you page, check if a variable in Session, ex: Session["synctoken"] if present. If no, then it is the first time, generate a token and store it there.
Every link request, ex: "mypage.aspx" put a get called synctoken with another token, diferent from the one you have stored in the Session, it goes like "mypage.aspx?synctoken=2iO02-3S23d".
Then, comming back to (2), in a request, if a token is present in Session check if the GET is present (Request.QueryString["synctoken"] != null). If no, send Error. If yes check whether the Tokens (Session and GET) are different. If they are different, it is ok, store the GET into your Session (Session["synctoken"] = Request.QueryString["synctoken"]) and go to step (2). If no, then the user refreshed the page, there goes your error.
It goes like:
if (Session["synctoken"] != null) {
if (Request.QueryString["synctoken"] != null) {
if (Request.QueryString["synctoken"].ToString().Equals(Session["synctoken"].ToString())) {
// Refresh! Goto Error!
MyUtil.GotoError();
}
else {
// It is ok, store the token and go on!
Session["synctoken"] = Request.QueryString["synctoken"];
}
}
else {
MyUtil.GotoErrorPage();
}
}
else {
Session["synctoken"] = MyUtil.GenerateToken();
}
Sorry if I could not be more clear.. good luck!
You can do that, but I'm sure you shouldn't. The user is in control of the browser, and if she feels like refreshing, it your job to make sure the page refreshes. Returning an error page is the wrong answer.
you can use client side hidden variable to store a counter or you can put counter in session. Well I would suggest you to expire the page on refresh there are ways you can achieve this disable cache etc [like all banks website do].