C# .NET - Response.Redirect(Request.UrlReferrer.AbsoluteUri);

Asked By sara asa on 08-Nov-13 01:23 PM
i have a page that should be login to access...so after login i need back to this page.i use this code
Response.Redirect(Request.UrlReferrer.AbsoluteUri);
in my login page till after login my user back to his priviouse page..but after login it stop in  login page and dont work at all.
how  can i solve this problem?
i dont want use cookies i just want use this line code to back to priviouse page after login.
Robbe Morris replied to sara asa on 08-Nov-13 01:23 PM
If your user hits your page via a browser favorite, the UrlReferrer will be null triggering a runtime exception as you try to use .AbsoluteUrl.

Here's the deal on this.  Looks like you are attempting to create a friendly UI where someone browses to a given page that requires them to be logged on.  That's good.  People like that.  Of course, you'd redirect them to the login page and want them automatically redirected back to the page they originally wanted to work on.

In order to do this "reliably" in "all" cases, you'll want to create a Session variable called LoginRedirectUrl as a string.  Populate the session variable with the desired Url to return to after logging in.  And, right after a successful login, put LoginRedirectUrl in a local string variable and then clear this Session variable before executing the Response.Redirect back to the url contained in the local string.

var url = Session["LoginRedirectUrl"].toString();
Session["LoginRedirectUrl"] = null;

Response.Redirect(url);
   
sara asa replied to Robbe Morris on 09-Nov-13 03:12 AM
yes with session it worked good.actually i used in first page that i need its url in cb wrote :
 session["rememberme"]=request.urlReferre;
response.redirect("~/login.aspx");

then  in login page cb i wrote :

response.redirect(session["rememberme'].tostring());
till today it is working good but still i didnt test all my project because it didnt get finished.ofcourse i have bad feeling about it for all cases and reliable so i would try your code too because maby it just work for one page not all cases.thank you.