ASP.NET login control - asp.net

I intend to use membership.authentication/authorization API from ASP.NET 2.0 in in ASP.NET 3.5 web app. However, when I implement the LoggedIn method for a login component as below:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
Label1.Text = User.Identity.Name;
}
the Name comes as a null value... the username/pass are correct, the login control works fine if the default behavior is used, but it seems that the Identity is not properly initialized. Any ideas on how to get the current User object with the associated values?
Thanks

You may need to check User.IsAuthenticated is true first

You can use Membership.GetUser method to accomplish the same thing:
Label1.Text = Membership.GetUser().UserName

Related

session variable for username

Hey I am creating a forum where users can login and post ocmments in a forum, I want the username as a session variable so I can get it when they post a comment and insert the username in the db and also to display a hello user message.
Below is my login code:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
localhost.Service1 myws = new localhost.Service1();
ds = myws.GetUsers();
foreach (DataRow row in ds.Tables[0].Rows)
if (txtusername.Text == System.Convert.ToString(row["username"]) &&
txtpassword.Text == System.Convert.ToString(row["password"]))
{
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false);
}
else
Label3.Text = "Invalid Username/Password";
}
Do I declare the session variable here?
Like:
Session["username"] = "username";
Also not sure what to type to get the value username from the db
Thanks
You don't need to use a session. Once you call the FormsAuthentication.RedirectFromLoginPage method, inside the target page you could access the currently connected user from the authentication cookie that was emitted by this method using User.Identity.Name.
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
// ...
}
}
To learn more about how Forms Authentication works in ASP.NET I invite you to read the following article.
You are already using forms authentication (FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false)) which is great. Consequently, you don't need to store the username is session as it's already available via User.Identity.Name, as Darin noted.
I have written two tutorials on forms authentication you might find useful:
An Overview of Forms Authentication
Forms Authentication Configuration and Advanced Topics
Additionally, consider using Membership. Membership is a subsystem built into ASP.NET that handles user accounts and provides an API for creating accounts, deleting accounts, etc. In short, you don't have to write all that code yourself. And with the login Web controls, creating new accounts, signing users in, resetting passwords, and so on, are all quite simple and involve zero to little code. For more information see my Membership tutorials.
Happy Programming!

Passing querystring with login control in asp.net 4?

Scenario:
I am doing project in C# ASP.NET 4.
I have a page of question. When somebody clicks on question (ie a Link Button) he is redirected to page where user can give answer but first he needs to login. So I put Login to Answer button that redirects user to GuestLogin.aspx with question id like this :
protected void LoginToAnswwer_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("~/GuestLogin.aspx?qid=" + qidrequest);
//This is working OK
}
And then when I am redirected to GuestLogin.aspx, I am putting below code in LoginButton of built in Login Control.
protected void LoginButton_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("QDisplay.aspx?qid=" + qidrequest);
}
Which is not working.
Question:
How to pass querystring with login button of built login control in asp.net 4 ?
You could pass a return URL to the login page, like this:
Response.Redirect(String.Format("/auth/login.aspx?return={0}", Server.UrlEncode(Request.Url.AbsoluteUri)));
In the login page, after authenticating the user:
Response.Redirect(Request.QueryString["return"]);
Pass Parameters from One Page to Another Page using QueryString :
//Set the Querystring parameters
Note: Maximum length of the
string that can be passed through QueryString is 255.
string URL =“QueryString.aspx?Name=” + txtFirstName.Text + “&Address=” + txtAddress.Text + “&City=” + txtCity.Text ;
//After Setting the Querystring Paramter values Use Response.Redirect to navigate the page
Response.Redirect(URL);
In the Page Load Event of the Navigated
Page,You can access the querystring parameter values like below :
lblName.Text = Request.QueryString["Name"].ToString();
lblAddress.Text = Request.QueryString["Address"].ToString();
lblCity.Text= Request.QueryString["City"].ToString();
That's how you have to use QueryString for passing parameters

How to pass variable from page to another page in ASP.NET

I want to ask how to pass a variable from a page to another page.
example.
in (page1.aspx.cs) there is button click and textbox
protected void Button1_Click(object sender, EventArgs e)
{
textbox1.text = ;
}
in (page2.aspx.cs)
A = "hello"
// A is variable that can be change, A variable is coming from microC
What I want is show "hello" from page2 in textbox1.text when I click button1 in page1.aspx
You can pass the value as a querystring parameter.
So if you are using Response.Redirect you could do something like
protected void Button1_Click(object sender, EventArgs e){
Response.Redirect("Page2.aspx?value=" + taxtbox1.text);
}
On Page 2 you can get the value using Request["value"].ToString()
Notice that the querystring parameter name is what you request. So if you have ?something=else you will Request["something"]
One way is to place the value into some form of temporary storage: Cookie, Session, etc. And then redirect.
Another would be to redirect with a query string value. It really depends on your situation.
I'd recommend setting a session if this is necessary.
Session["sessionname"] = "";
Though it isn't ideal, is it possible to have everything on page1? You can switch with a panel control.
Without a Postback it is not possible!
With a Postback, yes it is (see Cross Page Postback). Also see in the link what you can have access to! (Access possibilities are page controls & public members).
Other options, Session variables, cookies, query string, etc!
u can use one of this ways:
1- Query string
page.aspx?ID=111&&Name=ahmed
2- Session
Session["session1"] = "your value";
3- Public property
public String prop1
{
get
{
return txt_Name.Text;
}
}
4- Controls Data
5- HttpPost

ASP.NET problem with session / redirect to page

Hi I have problem with store user name in Session. On log on page I store user name to session. User input credentials on logon page and then is redirect on default page. I need in class Default access to variable store in session.
Logon.aspx
<script runat="server">
void Login_Click(object sender, EventArgs e)
{
Session["user"] = tbUserName.Text;
//You can redirect now.
Response.Redirect(FormsAuthentication.GetRedirectUrl(tbUserName.Text,
false));
}
</script>
secod main page is here:
Default.aspx-Default.aspx.cs
public partial class Default : Page,
IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
string userName = (string) (Session["user"]);
}
but result is that userName is empty.
Web config is here:
<sessionState cookieless="true" regenerateExpiredSessionId="true" />
Thank you for advice.
If the snippet is on the module level (as alluded to by Bala R in the comments) the session state has probably not been set yet. Try getting it in a method that is part of the page life cycle (like page_load, etc.).
Why not get it directly from HttpContext HttpContext.Current.User.Identity.Name
Edit: I guess you are trying to get it at page level instead of in page_load or another place. That's why you are not getting a session value.
I hope below will work for you
protected void Page_Load(object sender, EventArgs e)
{
string userName = (string) (Session["user"]);
}
Update: This is incorrect.
You're losing the (cookieless) session when you redirect. Cookieless sessions are maintained in the URL, and are lost when you explicitly redirect, so there is nothing in the session on your second page.

Is there a way to find out the age of an asp.net session?

How do I find out how old an asp.net (3.5) session is?
Not directly I think, but it would be easy to do it yourself. In global.asax you can add code to the Session_Start even handler where you add a session variable that tells when the session was created.
Something like this:
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["SessionStartTime"] = DateTime.Now;
}
Then you can check how long the session has existed by doing the following in your code:
TimeSpan sessionLifeTime = DateTime.Now - (DateTime)Session["SessionStartTime"];

Resources