Get users current page when session times out - c#

Lots and lots of examples out there as to how to set and redirect when the session times out. But nothing that I could find for this situation.
A typical situation where a timeout control monitors the session timeout and displays a window warning the user of that when there is 1 minute left. When the session times out, the user is redirected to a page (sessionexpired.aspx) that clears the session and displays information informing the user that they are required to login again.
I would like to log the page the user was on when the session actually timed out and do that in the code behind of the sessionexpired.aspx page.
Any help would be very welcome!

Try looking at the Referer from the current Request object. It's usually found using this:
Request.UrlReferrer
I hope this helps.

You can use one of these code examples to get the current page the user is on:
// Returns something like "http://www.example.com/myUrl/MyPage.aspx"
string page = HttpContext.Current.Request.Url.AbsoluteUri;
// Returns something like "/myUrl/MyPage.aspx"
string page = HttpContext.Current.Request.Url.AbsolutePath;
// Returns something like "MyPage.aspx"
string page = HttpContext.Current.Request.Url.AbsolutePath.Substring(url.LastIndexOf('/') + 1);
So wherever your code is to log you out when your session expires (probably in your master page), just add one of these lines.
Once you have it, you can add it as a query string parameter to your login page or you can save it in a database.

Related

How to check for session null on master page without logging out

I have a problem with reading value from session on every page load. I have to check if this session value is null on master page because I need to show the user real name when it's logged in so i can't rely only on forms authentication.
I'm also doing the same thing on every page load.
if (Session["Nome"] == null)
{
FormsAuthentication.RedirectToLoginPage();
}
I'm not sure why or if it's due to slow loading but even when i'm still authenticated i get redirected to login so at some point the session is null. I was wondering if is there a better way to show user name(not username) on master page and redirect to login page when the variable is actually null.
Well by default Session variables have a time span of 20 minutes, so if you are not refreshing the variable it will be null after the time span passes. So you either have to reset the time span for the "Nome" variable ( not recommended as staying on one page for 21 minutes would force the user to re login after another postback ) or check
if(!HttpContext.Current.User.Identity.IsAuthenticated)
FormsAuthentification.RedirectToLoginPage();
var username = HttpContext.Current.User.Identity.Name;

Registering a new user overwrites current user session - why?

I've come across an issue when registering new users with my app. The behaviour looks to be by design, but I don't understand why.
My problem is as follows (and I know it's a bit of an edge case):
User browses to my site's login page in two separate tabs in the same browser.
In the first tab, the user logs in and is correctly redirected to my home page.
In the second tab, the user follows my signup logic (which doesn't require any kind of page refresh, it's all done with client side code that culminates in a jQuery AJAX POST to the built in ServiceStack RegistrationService's /register endpoint)
Instead of creating a new user, the second user's details overwrite that of the logged in user's UserAuth record, and the first user can no longer log in.
Looking at the code in ServiceStack.ServiceInterface.Auth.RegistrationService, this behaviour appears to be 100% intentional:
var session = this.GetSession();
var newUserAuth = ToUserAuth(request);
var existingUser = UserAuthRepo.GetUserAuth(session, null);
var registerNewUser = existingUser == null;
var user = registerNewUser
? this.UserAuthRepo.CreateUserAuth(newUserAuth, request.Password)
: this.UserAuthRepo.UpdateUserAuth(existingUser, newUserAuth, request.Password);
Once the first user is logged in, the session cookie for that user gets sent with the registration request, causing the existingUser variable in the code above to be populated with the UserAuth for that user, which is then updated with the registering user details.
Can anyone explain why the code's been written in this way? And is there any way around it without replacing the RegistrationService with my own implementation?
This is the feature that lets you to auto-merge different Auth Providers into the same account in ServiceStack.

How to count Number of refreshes of web page

I have a web form of Asp.Net, in which I want JavaScript to count how many time i have refreshed the page.
If you want to do it on clientside just save (and retrieve) the information on localstorage every time load event occurs
Do you want to count this per user ? Or for whole application ?
If you are doing for whole application you can use application variable in Global.asax on each page request . But that might get lost if your application recycles .
If you want to do for each user You can use server side sessions or cookies on clientside .
You can set the value in a cookie using js or asp, or in a session value (for a single user) or in application value (for all the users), is not necessary javascript.
You have to put this code server side on page load.
For all users:
Application["refresh_count"] =
Convert.ToInt64(HttpContext.Current.Application["refresh_count"]) + 1;
For a single user with session:
Session["refresh_count"] = Convert.ToInt64(Session["refresh_count"]) + 1;
OR
Response.Cookies["UserSettings"]["refresh_count"] = Convert.ToInt64(Response.Cookies["UserSettings"]["refresh_count"]) + 1;
Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);
You can save this in the Session Object.
You can use jQuery calling prepared address.
For example:
$.ajax({
url: ".../countPageRefreshes.aspx",
data: { page: "thisPageAddress" }
})
Then, in countPageRefreshes you can increase number of times, page was refreshed and save it somewhere.

How to retrieve site root url?

I need to get the url of the site so that I render a user control on only the main page. I need to check for http://foo.com, http://www.foo.com, and foo.com. I am a bit stumped as to how check for all 3. I tried the following which does not work.
string domainName = Request.Url.Host.ToString();
if (domainName == "http://nomorecocktails.com" | Request.Url.Host.Contains("default.aspx"))
{ //code to push user control to page
Also tried
var url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/";
Any thoughts?
You need to check if the Request.Path property is equal to / or /Default.aspx or whatever your "main page" is. The domain name is completely irrelevant. What if I accessed your site via http://192.56.17.205/, and similarly, what if your server switched IP addresses? Your domain check would fail.
If you utilize the QueryString to display different content, you'll also need to check Request.QueryString.
Documentation for Request.Path:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.path.aspx
Documentation for Request.QueryString:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring.aspx
If you need the user control to only appear on the main page (I'm assuming you mean home page), then add the code to call the user control to the code behind of that file.
If this code is stored in the master page, then you can reference it like:
Master.FindControl("UserControlID");
If you are only using the one web form (ie. just Default.aspx), then you can check that no relevant query strings are included in the URL, and display only if this is the case:
if (Request.QueryString["q"] == null){
//user control code
}
However if you are using this technique then I would recommend using multiple web forms using master pages in the future to structure your application better.
The ASP.NET website has some good tutorials on how to do this:
http://www.asp.net/web-forms/tutorials/master-pages

clear session on every first visit

I have a facebook application which is session based. i am having bad behaviour as follows: if the user is using the app then logs out from facebook and some other user logs in to facebook and logs in the app they see the user data who just logged out.
Essentially I d like to clear the session every time visitor hits the first page.
I have a HomeController which extends BaseController in base controller i check if the user has a session.
where should i put Session.clear() in order to prevent user to access old user session?
on
HomeController{
[authorize for facebook]
indexAction{
redirect to home action
}
}
my concern is that when indexaction is invoked Before that base controller will be invoked and i will get a infinite loop.
Note: I m using a UserCookie which i store the user id and expiration of the cookie within.
any ideas?
It looks like you want to check if Facebook user ID matches data in session state. The easiest would be to put something like Session["FBID"]=facebookId and than check on every request if current facebookId matches `Session["FBID"], if not - clear session (irrespective of current location).

Categories