asp.net tracking user info - asp.net

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

Related

Access Session object at Session_End Event in Globle.asax file

I want to access session variable at Session_End event of globle.asax file.But HtppContext.Current returns null. Please suggest any other way.
protected void Session_End(object sender, EventArgs e)
{
if (HttpContext.Current != null)
{
HttpContext ht = HttpContext.Current;
string username = ht.Session["UserName"].ToString();
}
}
I was facing the same problem yesterday, and I simply use:
string username = Session["UserName"].ToString();

get username after login

I want to get the username after login but it doesn't work.
public partial class Login : System.Web.UI.Page
{
string strUser;
protected void Login1_LoggedIn(object sender, EventArgs e)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
}
This is my error:
Membership.GetUser().UserName is null, because the new principal object is not attached to the current HttpContext object yet.
So you need to explicitly retrieve that recently logged-in user using username from Login control.
Update: Credit to jadarnel27
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
// Get the username from login control and retrieves the user info explicitly
Membership user = Membership.GetUser(Login1.Username);
...
}
You need to check and make sure the user's login was successful. It looks like you're just using standard ASP.NET membership, so this should work:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if(e.Authenticated)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
else
{
strUser = "Login Failed!";
}
}
It's been a while since I worked with these controls, but you might need to determine the value of e.Authenticated yourself first and set it. If so, you need to put this before the if-block I wrote above:
bool authenticated = Membership.ValidateUser(Login1.UserName, Login1.Password);
e.Authenticated = authenticated;
I think vanilla ASP.NET membership handles that part for you; if you were using a custom authentication scheme, you would definitely need to do that step.

Cookie does not work in asp.net

I have two pages, test1.aspx and test2.aspx
test1.aspx has this
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test", "test");
cookie.Expires = DateTime.Now.AddDays(1);
Response.SetCookie(cookie);
}
test2.aspx has this
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Response.Cookies["test"].Value);
}
The value of the cookie is null, no matter how many times I tried. I tried to open page1 and then page 2, expecting a cookie to work, but it is not working, I don't know why.
I think you need to read off the Request instead of the response.
As MSDN suggestions
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Cookies["test"].Value);
}
In a web application, the request comes from the client (browser) and the response is sent from the server. When validating cookies or cookie data from the browser you should use the Request.Cookies collection. When you are constructing cookies to be sent to the browser you need to add them to the Response.Cookies collection.
Additional thoughts on the use of SetCookie
Interestingly for HttpResponse.SetCookie as used on your first page; MSDN says this method is not intended for use in your code.
This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
Even the example code found on this page uses the Response.Cookies.Add(MyCookie) approach and does not call SetCookie
You need is :
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Cookies["test"].Value);
}
There is a sample here:
Reading and Writing Cookies in ASP.NET and C#
Regards
Save cookie with (response) and read cookie by (request)
//write
response.cookies("abc") = 123;
//read
if ((request.cookies("abc") != null)) {
string abc = request.cookies("abc");
}
Use Response.Cookies.Add(cookie);
Reference: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cookies
On page test2.aspx
You should try this
protected void Page_Load(object sender, EventArgs e)
{
var httpCookie = Request.Cookies["test"];
if (httpCookie != null)
{
Response.Write(httpCookie.Value);
}
}

Passing the value of a XML tag to another page

Here is the page where I am retrieving from a XML page and by storing it in cookie, I want to retrieve it in another page.
public partial class shopping : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie userCookie = new HttpCookie("user");
userCookie["quantity"] = TextBox1.Text;
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("shopping_cart.xml"));
XmlNode root = doc.DocumentElement;
if (RadioButton1.Checked)
{
string str1 = doc.GetElementsByTagName("cost").Item(0).InnerText;
userCookie["cost"] = str1;
//Label3.Text = str1;
Response.Redirect("total.aspx");
}
}
}
and here is other page where I am trying to retrieve it (total.aspx.cs):
public partial class total : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
**Label2.Text = Request.Cookies["user"]["quantity"];**
}
}
I am getting a Null Reference on the line which is in bold. Any suggestions on how can I do it?
You created the cookie in the first section, but forgot to append it to the Response.
Response.Cookies.Add(userCookie); // place before your Response.Redirect
Also, be aware that cookies have a useful maximum size of 4000 bytes, and otherwise a probably not the best choice for what you are doing. You may wish to store temporary session info in the Session for access between pages, rather than use a cookie.
Session["quantity"] = TextBox1.Text
// ...
Session["cost"] = str1;
and in the second page
Label2.Text = Session["quantity"] as string;

Set session variable in Application_BeginRequest

I'm using ASP.NET MVC and I need to set a session variable at Application_BeginRequest. The problem is that at this point the object HttpContext.Current.Session is always null.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
//this code is never executed, current session is always null
HttpContext.Current.Session.Add("__MySessionVariable", new object());
}
}
Try AcquireRequestState in Global.asax. Session is available in this event which fires for each request:
void Application_AcquireRequestState(object sender, EventArgs e)
{
// Session is Available here
HttpContext context = HttpContext.Current;
context.Session["foo"] = "foo";
}
Valamas - Suggested Edit:
Used this with MVC 3 successfully and avoids session error.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context != null && context.Session != null)
{
context.Session["foo"] = "foo";
}
}
Maybe you could change the paradigm... Perhaps you can use another property of the HttpContext class, more specifically HttpContext.Current.Items as shown below:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext.Current.Items["__MySessionVariable"] = new object();
}
It won't store it on the session, but it will be stored on the Items dictionary of the HttpContext class and will be available for the duration of that specific request. Since you're setting it at every request, it would really make more sense to store it into a "per session" dictionary which, incidentally, is exactly what the Items is all about. :-)
Sorry to try to infer your requirements instead of answering your question directly, but I've faced this same problem before and noticed that what I needed was not the Session at all, but the Items property instead.
You can use the session items in Application_BeginRequest this way:
protected void Application_BeginRequest(object sender, EventArgs e)
{
//Note everything hardcoded, for simplicity!
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("LanguagePref");
if (cookie == null)
return;
string language = cookie["LanguagePref"];
if (language.Length<2)
return;
language = language.Substring(0, 2).ToLower();
HttpContext.Current.Items["__SessionLang"] = language;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
}
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context != null && context.Session != null)
{
context.Session["Lang"] = HttpContext.Current.Items["__SessionLang"];
}
}

Resources