Accessing Sessions Variables in code behind - asp.net

Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Session["Authenticated"] )
{
Response.Redirect( "index.aspx", false );
}
}
Once they login I set the session to true. Basically, if they don't have an active session I want them re-directed back to the index/login page. How do I accomplish this?

Use this check
if(Session["Authenticated"] == null || !(bool)Session["Authenticated"])

If you are using cookie, you can store a marker in your cookie so you can tell the difference between "fresh browser + new session" and "old browser + expired session".
Below is sample code that will redirect the user to an expired page if the session has expired.
void Session_OnStart(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;
if (cookies["starttime"] == null) {
HttpCookie cookie = new HttpCookie("starttime", DateTime.Now.ToString());
cookie.Path = "/";
context.Response.Cookies.Add(cookie);
}
else {
context.Response.Redirect("expired.aspx");
}
}
And if you are trying to implement sessions this might help you http://aspalliance.com/1621_Implementing_a_Session_Timeout_Page_in_ASPNET.2

Related

asp.net tracking user info

How is the best way to track user information, sesssion Id, cookies? once for user session.
In Default.aspx:
protected void Page_Load(object sender, EventArgs e)
{
IF (!isPostPack)
{
var sessionValue= System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null ? System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
cONSOLE.WRITELINE(sessionValue);
}
}
This is not optimize. is there anyway to get only once the session iD,per user?
var sessionValue = System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"]
!= null ?
System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
All that will give you is the identifier that ASP.Net uses to track the session. This is rarely something you need to directly access in code.
But assuming that is what you want, it will be extremely fast. To make it cleaner, you can:
Access Request directly (no need for HttpContext inside a Page)
Store the value in a class-level variable that will live for the lifecycle of the page.
private string _sessionId;
protected void Page_Load(object sender, EventArgs e)
{
_sessionId = Request.Cookies["ASP.NET_SessionId"] != null
Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
}
If you want to do this only once per session (per the comments):
protected void Session_Start( object sender, EventArgs e )
{
using( var writer = File.CreateText( #"c:\temp\session-id.txt" ) )
{
writer.WriteLine( Session.SessionID );
}
}

how to show the message for session expired in asp.net using httpcontext

Redirecting user to login page after session timeout is similar to refreshing the page after certain intervals method. Only thing which will differ is that calculating time after which the page has to be redirected. Hence time can be calculated using Session.timeout property which will give us session timeout value for that session. Add some grace timings to that value and redirect the user to the login page automatically.
protected void Page_Init(object sender, EventArgs e)
{
CheckSession();
}
private void CheckSession()
{
if (Session["SessionID"] == null)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "var r = confirm('Your Session Has Expired'); if (r == true) var str= 'PartnerLogin.aspx'; location.href = str ;", true);
}
}

How to properly authenticate mvc-mini-profiler with AspNetSqlMembershipProvider

I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hit and Authenticate it's hit with some of the request and the profiler does not show up.
Checking only for Request.IsLocal works fine.
if(Request.IsAuthenticated)
{
if(User.IsInRole("Admin");
MiniProfiler.Start();
}
Any idea or why it's not working or better way to do it?
[Update] I accepted the awnser but undid it as I didn't quite get it do work
I did the following but the profiler is not showing up at first.
After a few tries it started showing up, even when I tried to acess the site with incognito mode, so no cookie.
protected void Application_PostAuthorizeRequest(Object sender, EventArgs e)
{
if (User.IsInRole("Admin"))
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if (cookie == null)
{
cookie = new HttpCookie("RoleProfiler");
cookie.Value = "yes";
cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
}
}
}
And I'm checking with
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if ((cookie != null) && (cookie.Value == "yes") )
{
MvcMiniProfiler.MiniProfiler.Start();
}
}
And ending at the end of the request.
protected void Application_EndRequest()
{
MvcMiniProfiler.MiniProfiler.Stop();
}
[Update2] Closing question, ignore this, I was being owned by outputcache.
The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:
protected void Application_BeginRequest()
{
MvcMiniProfiler.MiniProfiler.Start();
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(!CurrentUserIsAllowedToSeeProfiler())
{
MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}
}
Begin request happens before the user is fully authenticated in the request life cycle.
I solved this issue by adding a cookie if the user is in a role ("Admin" in your case) when the request is authenticated then you can check for this cookie on begin request and initialise the profiler.
It wont't work the first time but should every time after that.
This is my 2cent.
context.AcquireRequestState += (sender, e) =>
{
// Check debug in session. Can be set from Querystring. (?debug=true)
if (HttpContext.Current.Session != null && HttpContext.Current.Session["Debug"] != null)
{
try{
bool debug = (bool)HttpContext.Current.Session["Debug"];
if (debug == true)
MiniProfiler.Start();
else
MiniProfiler.Stop(discardResults: true);
}
catch{
MiniProfiler.Stop(discardResults: true);
}
}// Or always show if Administrator.
else if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
bool admin = HttpContext.Current.User.IsInRole("Administrator");
if (admin == false)
{
MiniProfiler.Stop(discardResults: true);
}
}
else
{
MiniProfiler.Stop(discardResults: true);
}
};

Asp.NET cookies returning null

I'm trying to save a cookie when a button is clicked like so...
protected void btn_login_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test");
cookie["work"] = "now";
cookie.Expires = DateTime.Now + new TimeSpan(1, 0, 0, 0);
cookie.Domain = ".cookie.com";
Response.Cookies.Add(cookie);
}
Then on the page_load I am reading the cookie...
protected void Page_Load(object sender, EventArgs e)
{
string a = Response.Cookies["test"]["work"];
}
But it keeps coming back null. I am running this under localhost and I read that cookies won't save under localhost so I edited my host file to say
127.0.0.1 test.cookie.com
When I used Fiddler to see what was getting posted to the header of the page. It looks like this...
test/work = now
test =
So I can see that it is getting set but for some reason when I read it in it returns null.
On the page_load change it from Response.Cookies to Request.Cookies.
The Response object is for sending data back. The Request object has data that is passed to you.
example:
String a = Request.Cookies["test"]["work"];
Note that if the cookie doesn't exist, then this will cause a null reference exception.
Usually you should do something like:
protected void Page_Load(object sender, EventArgs e) {
HttpCookie cookie = Request.Cookies["test"];
String a = String.Empty;
if (cookie != null) {
a = cookie["work"];
}
}
Try this
Response.Cookies["work"].Value = "Value1"
Refer this for more information.
On pageload for reading the cookie try
string value = Request.Cookies["work"].Value

ASP.NET Forms Authentication with Windows Safari

Does anyone know why ASP.NET Forms Authentication does not work on windows safari, or better yet, how to get it to work? It seems like a very weird issue. When I use a login control (System.Web.UI.WebControls.Login) everything works fine, but if I try to do a custom Forms Authentication login when I call FormsAuthentication.RedirectFromLoginPage safari just sends me back to the login page as if I'm not authenticated whereas every other browser logs me in and sends me on my way.
protected void lnkLogin_Click(object sender, EventArgs e)
{
if (Membership.Provider.ValidateUser(txtUsername.Text, txtPassword.Text))
{
Session.Clear();
HttpContext.Current.Response.Cookies.Clear();
FormsAuthentication.SetAuthCookie(txtUsername.Text, true);
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
}
Try either SetAuthCookie, or RedirectFromLoginPage. The redirect needs to know where to redirect to anyway (ReturnUrl), maybe that is your problem.
if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage("someuserid", false);
}
else
{
FormsAuthentication.SetAuthCookie("someuserid", false);
Response.Redirect("~/SomePage.aspx");
}
This works fine for me in Safari:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
//check login
User user = UserBAL.GetUser(Login1.UserName, Login1.Password);
//null and filled object check
if (user != null && user.Id > 0 && user.Roles != null && user.Roles.Count > 0)
{
e.Authenticated = true;
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, //version
Login1.UserName, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
string.Join("|", user.Roles.ToArray())); // User ata
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
Response.Cookies.Add(authCookie);
//redirect
Response.Redirect(FormsAuthentication.GetRedirectUrl(
Login1.UserName,
false));
}
else
{
Login1.FailureText = "Login failed.";
}
}

Resources