get username after login - asp.net

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.

Related

web service is unable to return back to default page

I have asmx web service hosted on IIS and its purpose is to authenticate logined user.
when I run my code using visual studio and debug service is successfully called and authenticate user from DB but it is unable to transfer control back to my code that has default page.
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
Response.Redirect("Default.aspx");
Response.Cache.SetNoStore();
if (!Page.IsPostBack)
{
Session["Uri"] = Request.UrlReferrer;
}
this.hdnLoginStatus.InnerHtml = "";
if (!Page.IsPostBack)
{
new DAS().AuthenticateRequest();
if (HttpContext.Current.Items["LoginStatus"] == null)
return;
var key = (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"];
string msg = (string)GetGlobalResourceObject("Message", key.ToString()) ?? "";
this.ShowMessage(msg, MessageType.Warning);
this.hdnLoginStatus.InnerHtml = "SignedOutForcefully";
}
}
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?key=" + (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"]);
}

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

ASP Membership Current user not taking the right value

i am using an ASP control Login and i want to redirect the user logged in depending on its role. But it seems like The User take the previous value of the last logged in user. seems problem of refresh the current user or something like this
Code of my webform1.aspx.cs:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
TextBox1.Text = Context.User.Identity.Name.ToString();
if (Context.User.IsInRole("admin"))
{
Response.Redirect("~/admin.aspx");
}
else if (User.IsInRole("user"))
{
Response.Redirect("~/user.aspx");
}
}
Inside LoggedIn event of Login control, principal object hasn't been attached to the current HttpContext yet.
Therefore, you cannot use Context.User inside LoggedIn event.
protected void Login1_LoggedIn(object sender, EventArgs e)
{
var roles = Roles.GetRolesForUser(Login1.Username);
if (roles.Contains("admin"))
{
Response.Redirect("~/admin.aspx");
}
else if (User.IsInRole("user"))
{
Response.Redirect("~/user.aspx");
}
}

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;

Resources