Server.Transferrequest() and getting the current URL - asp.net

Say in my 'Page_init()' of "a.aspx" i just have 'server.transferrequest("b.aspx").
This works great, displays the content for "b.aspx" and the browserurl still stays at "a.aspx".
Happy days.
However does anyone know how to see this url from my "b.aspx" (the resulting page)?.
The usual request.rawurl and request.url.absoluteuri both return the current page as "b.aspx".

Server.TransferRequest performs an asynchronous execution of the specified URL. This means that your client has no clue of was is going on at the server so from your client perspective it's the same page.
If you need to change the actual page (which is the most common) then use Response.Redirect.

Maybe before you do the transfer you could save the information you need somewhere, then retrieve it when it's needed again.

You can use PreviousPage to get source page that makes server transfer :
string previousPagesUrl = PreviousPage.Request.RawUrl;
EDIT : #maxp, as an answer to your comment, PreviousPage only works for Server.Transfer and cross page postback.
You'll get null for PreviousPage if :
the source page redirects to the destination page.
a link at source page forwards the page to destination page.

NameValueCollection headers = new NameValueCollection();
headers["RawUrl"] = HttpContext.Current.Request.RawUrl;
Server.TransferRequest("b.aspx", true, null, headers);
And then use Headers["RawUrl"] in b.aspx.

Have you tried this method:
public void Transfer(string path, bool preserveForm )
http://msdn.microsoft.com/en-us/library/caxa892w.aspx
I currently got in the same problem, and I found out that Server object has this parameter on transfer method that gives you the posibility to preserve the original request form or not.

Related

Pass parameter from 1 page to another using post method

I have a page "Demo.aspx". I need to set some parameters using post method and redirect the page to "DemoTest.aspx".
Is there any way to set parameters in post method in asp.net? I don't want to set "Querystring" due to security propose.
Also I need server side code for this. I am not able to use "Javascript" or "Jquery" for the same.
Here is some more description for the same.
Right now I am using Response.Redirect("www.ABC.Com/DemoTest.aspx?P1=2"). So the page is simply redirect to the given URL.
Now I don't want to pass that "P1" in "Querystring". Instead of query string I want to use Post method.
Please note that redirection page is not in my own application. So I cant maintain session or "Viewstate".
Thanks in advance.
Use a session variable and response.redirect to the next page.
Session["MyVariable"] = "someThing";
Response.Redirect("DemoTest.aspx");
The value stored in Session variables will be accessible across application.
you can store in session like this :
Session["id"] = "anyID";
To get values On another page you need to write
string id = Convert.ToString(Session["Id"]);
However
By default, in .NET pages post() do the things automatically.
You will need to do sumthing like this:
Server.Transfer("DemoTest.aspx", True)

Passing data between different URLs

I need to check where did the incoming request came from before loading a page
ex:
for user to view www.mysite/page1.aspx
request should come through www.othersite/page1.aspx
so on page1 load in mysite i need to check whether the request came from page1 in othersite.
i have tried Page.Request.UrlReferrer but i saw there some posts which tells every browser might not support Page.Request.UrlReferrer.
i can not pass visible parameters on URL.
This is a common issue when you do not want to allow request from arbitrary sites.
What you can do is, create a variable in session and put this variable in the Page1.aspx. When the page posts back, you should get that variable back and it should also match the one stored in the session. If it does not, you can be sure that the request is from some other server.
You can use PostBackUrl on the start page
And access your parameters with PreviousPage in the arrived page
if (this.PreviousPage != null)
{
var control = Page.PreviousPage.FindControl("..."); //Adjust your Id and add cast
}
Nota : This was also created to provide greater security redirection setting.

Retrieving HTML from ASP.NET page on postback

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();
}

Using endResponse in a Response.Redirect

While performing a response.redirect in an ASP.NET page, I received the error:
error: cannot obtain value
for two of the variables being passed in (one value being retrieved from the querystring, the other from viewstate)
I've never seen this error before, so I did some investigating and found recommendations to use the "False" value for "endResponse"
e.g. Response.Redirect("mypage.aspx", False)
This worked.
My question is: what are the side-effects of using "False" for the "endResponse" value in a response.redirect?
i.e. are there any effects on the server's cache? Does the page remain resident in memory for a period? Will it affect different users viewing the same page? etc.
Thanks!
From this other question and this blog post, the recommended pattern is-
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
This avoids the expensive ThreadAbortException/Response.End. Some code will be executed after the CompleteRequest(), but ASP.Net will close the request as soon as it is convenient.
Edit- I think this answer gives the best overview. Note that if you use the pattern above, code after the redirect will still be executed.
An MSDN blog post that might answer your question:
The drawback to using [Response.Redirect(url, false)] is that the page will continue to process on the server and be sent to the client. If you are doing a redirect in Page_Init (or like) and call Response.Redirect(url, false) the page will only redirect once the current page is done executing. This means that any server side processing you are performing on that page WILL get executed.
Response.Redirect(..., true) results in a ThreadAbortException.
depending on your exception handling setup you might get your log filled with error messages one for each redirect.

Checking The Date A Webpage Has Been Updated?

I want to be able to run a little script that I can populate with a list of URLs and it pulls in and checks when the page was last updated? Has anyone done this?
I can only find a manual way of doing this using JavaScript by pasting this into the browser URL field
javascript:alert(document.lastModified)
Any ideas greatly received :)
The following will step through an array of URLs and display the last modified date or, if it's not present, the date of the server request.
string[] urls = { "http://boflynn.net", "http://slashdot.org" };
foreach ( string url in urls )
{
System.Net.HttpWebRequest req =
(System.Net.HttpWebRequest) System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse resp =
(System.Net.HttpWebResponse) req.GetResponse();
Console.WriteLine("{0} - {1}", url, resp.LastModified);
}
If you use urllib2 (or perhaps httplib might be better still) in a python script you can inspect the headers that are returned for the last-modified field.
It depends on what you mean by "last updated". Sure, there is the Last-Modified HTTP header, but it can be very misleading. For example, if the page is being served up dynamically, there is a good change that this field will be the current time, even if the content of the page itself (the part useful to humans) has not been updated in a rather long time. This page itself is a good example of this phenomenon.
If you are truly interested in the last time the content was updated, then I don't have an immediate answer.

Resources