How can I get previous page url when i used location.href? - c#

I have used location.href to redirect next page, but now i want to back to this page, how can I do?
in my case, i cannot use Request.UrlReferrer.PathAndQuery, so any suggestion?

Since you are using location.href to change the URL, your browser is going to kick off a new request/response cycle. Thus to your server, there is no referrer - this is a whole new request.
The most direct approach to solve your problem would be to add a referrer-url parameter to your new URL, which you can then pick up on the server side.
eg:
control.location.href = "newpage.aspx?referrer-url=thispage.aspx";
and on the server:
string referrerUrl = Request["referrer-url"];

If the previous URL is one that you own/can predict (e.g. the user came from page A or page B), you could use a trick like this one: http://www.merchantos.com/blog/makebeta/tools/spyjax

Related

Why doesn't redirect work?

I am using this code to redirect to page and then want to activate a specific tab among several tabs but it doesn't work. Why ? I mean anything after redirect doesn't work or display. I debugged , it hits the code after redirect code but no effect on front end.
Response.Redirect(Request.RawUrl, false);
tabContainer.ActiveTabIndex = 1;
ShowMsg("Data Updated");
As you can see on MSDN Response.Redirect ends the current request immediately and navigates to the new Url. That is why your following code is not executed.
If you want to do some additional actions on the Url you redirect your response to, you should think about adding some Parameters, e.g. Url Parameters, that get evaluated by the new Url.
The false you are passing to the Response.Redirect just prevents that a ThreadAbortException is thrown.

Retrieve the Original (Client) Url Without the Default Document [duplicate]

I would like to get the exact url that user typed into the browser. Of course I could always use something like Request.Url.ToString() but this does not give me what i want in the following situation:
http://www.mysite.com/rss
With the url above what Request.Url.ToString() would give me is:
http://www.mysite.com/rss/Default.aspx
Does anyone know how to accomplish this?
I have already tried:
Request.Url
Request.RawUrl
this.Request.ServerVariables["CACHE_URL"]
this.Request.ServerVariables["HTTP_URL"]
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "CACHE_URL")
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "HTTP_URL")
Edit: You want the HttpWorkerRequest.GetServerVariable() with the key HTTP_URL or CACHE_URL. Note that the behavior differs between IIS 5 and IIS 6 (see documentation of the keys).
In order to be able to access all server variables (in case you get null), directly access the HttpWorkerRequest:
HttpWorkerRequest workerRequest =
(HttpWorkerRequest)((IServiceProvider)HttpContext.Current)
.GetService(typeof(HttpWorkerRequest));
Remember too that the "exact URL that the user entered" may never be available at the server. Each link in the chain from fingers to server can slightly modify the request.
For example if I type xheo.com into my browser window, IE will be convert to http://www.xheo.com automatically. Then when the request gets to IIS it says to the browser - you really want the default page at http://www.xheo.com/Default.aspx. So the browser responds by asking for the default page.
Same thing happens with HTTP 30x redirect requests. The server will likely only ever see the final request made by the browser.
Try using Request.Url.OriginalString
Might give you the thing you are looking for.
It is possible, you just need to combining a few of the values from the request object to rebuild the exact url entered:
Dim pageUrl As String = String.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Host,
Request.RawUrl)
Response.Write(pageUrl)
Entering the address http://yousite.com/?hello returns exactly:
http://yousite.com/?hello
Request.RawUrl
I think is the monkey you are after...
Easiest way to do this is used client-side programming to extract the exact url:
<script language="javascript" type="text/javascript">
document.write (document.location.href);
</script>

Passing parameters using Server.Transfer but not using query string

I have a registration form and want to transfer the user to the success page, telling him that an email was sent to his email. I need to transfer his email from the register page to the success page.
I found about Server.Transfer, but I can't find out how to send parameters. I don't want to use query string as I don't like revealing information in the URL.
What is the proper way (if possible) to do this?
Server.Transfer("destination.aspx", true)
You might see that the above code contains the name of the page to which the control is transferred and a Boolean value ‘True’ to indicate to preserve the current form state in the destination page.
Set a property in your login page and store in it, the email.
Once this is done, do a Server.Transfer("~/SuccessPage.aspx", true);
On the other page, where you redirected, you should check something like that :
if(this.PreviousPage != null) {
((LoginPageType)this.PreviousPage).MyEmailProperty;
}
When you using server transfer you just move execution to different server handler , user will no see the new url or the parameters so it safe to make this transfer.
I would rather recommend that you do it differently.
When the user clicks the register button, you verify it all and then send the email from the still current page (so you need not transfer data to another page at all). If all went well, you just redirect:
Response.Redirect("/order/success.aspx");
If something was wrong (validation errors, sending email caused an exception) you are still on the right page for a retry. I would not use Server.Transfer at all in most cases.
You'll have to persist the value somewhere. The obvious options are in the Session object, or in a database.
For this kind of use case. You can use Context.Items to save the data with a key and read the value using the same key in the child page you are doing the Server.Transfer. Context.Items are sort of per request scoped cache for you.
Context.Items['DataKey'] = Data;
Server.Transfer("~/AnyRouteRelativePath", true);

Truncating Query String & Returning Clean URL C# ASP.net

I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.
ie.
in: www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media
out: www.website.com/default.aspx
What would be the best way to achieve this?
System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:
string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
Uri uri = new Uri(url);
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
This gives the output: http://www.website.com/default.aspx
[The Uri class does require the protocol, http://, to be specified]
GetLeftPart basicallys says "get the left part of the uri up to and including the part I specify". This can be Scheme (just the http:// bit), Authority (the www.website.com part), Path (the /default.aspx) or Query (the querystring).
Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller.
Here is a simple trick
Dim uri = New Uri(Request.Url.AbsoluteUri)
dim reqURL = uri.GetLeftPart(UriPartial.Path)
Here is a quick way of getting the root path sans the full path and query.
string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");
This may look a little better.
string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);
if (rawUrl.Contains("/post/"))
{
bool hasQueryStrings = Request.QueryString.Keys.Count > 1;
if (hasQueryStrings)
{
Uri uri = new Uri(rawUrl);
rawUrl = uri.GetLeftPart(UriPartial.Path);
HtmlLink canonical = new HtmlLink();
canonical.Href = rawUrl;
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);
}
}
Followed by a function to properly fetch the application URL.
Works perfectly.
I'm guessing that you want to do this because you want your users to see pretty looking URLs. The only way to get the client to "change" the URL in its address bar is to send it to a new location - i.e. you need to redirect them.
Are the query string parameters going to affect the output of your page? If so, you'll have to look at how to maintain state between requests (session variables, cookies, etc.) because your query string parameters will be lost as soon as you redirect to a page without them.
There are a few ways you can do this globally (in order of preference):
If you have direct control over your server environment then a configurable server module like ISAPI_ReWrite or IIS 7.0 URL Rewrite Module is a great approach.
A custom IHttpModule is a nice, reusable roll-your-own approach.
You can also do this in the global.asax as you suggest
You should only use the 301 response code if the resource has indeed moved permanently. Again, this depends on whether your application needs to use the query string parameters. If you use a permanent redirect a browser (that respects the 301 response code) will skip loading a URL like .../default.aspx?utm_source=twitter&utm_medium=social-media and load .../default.aspx - you'll never even know about the query string parameters.
Finally, you can use POST method requests. This gives you clean URLs and lets you pass parameters in, but will only work with <form> elements or requests you create using JavaScript.
Take a look at the UriBuilder class. You can create one with a url string, and the object will then parse this url and let you access just the elements you desire.
After completing whatever processing you need to do on the query string, just split the url on the question mark:
Dim _CleanUrl as String = Request.Url.AbsoluteUri.Split("?")(0)
Response.Redirect(_CleanUrl)
Granted, my solution is in VB.NET, but I'd imagine that it could be ported over pretty easily. And since we are only looking for the first element of the split, it even "fails" gracefully when there is no querystring.

Get the exact url the user typed into the browser

I would like to get the exact url that user typed into the browser. Of course I could always use something like Request.Url.ToString() but this does not give me what i want in the following situation:
http://www.mysite.com/rss
With the url above what Request.Url.ToString() would give me is:
http://www.mysite.com/rss/Default.aspx
Does anyone know how to accomplish this?
I have already tried:
Request.Url
Request.RawUrl
this.Request.ServerVariables["CACHE_URL"]
this.Request.ServerVariables["HTTP_URL"]
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "CACHE_URL")
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "HTTP_URL")
Edit: You want the HttpWorkerRequest.GetServerVariable() with the key HTTP_URL or CACHE_URL. Note that the behavior differs between IIS 5 and IIS 6 (see documentation of the keys).
In order to be able to access all server variables (in case you get null), directly access the HttpWorkerRequest:
HttpWorkerRequest workerRequest =
(HttpWorkerRequest)((IServiceProvider)HttpContext.Current)
.GetService(typeof(HttpWorkerRequest));
Remember too that the "exact URL that the user entered" may never be available at the server. Each link in the chain from fingers to server can slightly modify the request.
For example if I type xheo.com into my browser window, IE will be convert to http://www.xheo.com automatically. Then when the request gets to IIS it says to the browser - you really want the default page at http://www.xheo.com/Default.aspx. So the browser responds by asking for the default page.
Same thing happens with HTTP 30x redirect requests. The server will likely only ever see the final request made by the browser.
Try using Request.Url.OriginalString
Might give you the thing you are looking for.
It is possible, you just need to combining a few of the values from the request object to rebuild the exact url entered:
Dim pageUrl As String = String.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Host,
Request.RawUrl)
Response.Write(pageUrl)
Entering the address http://yousite.com/?hello returns exactly:
http://yousite.com/?hello
Request.RawUrl
I think is the monkey you are after...
Easiest way to do this is used client-side programming to extract the exact url:
<script language="javascript" type="text/javascript">
document.write (document.location.href);
</script>

Categories

Resources