ASP.net page_load doesn't detect session - c#

I have a problem with using session variable in the page_load. I have a page (members.aspx) which is a members area.
If the user isn't logged in, it will display a form asking them to login. The form submits their details, checks if ok then sets session variables if OK. It then reloads the page.
So if the user has authenticated correctly, it sets Session["memberLoggedIn"] = true.
My page_load function then looks like this
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(Session["memberLoggedIn"]) == true) {
Response.Write("OK");
}
}
There is more code, but essentially, the "OK" should be written. However, it doesn't appear. Even though the session IS set. If I go to the page directly it will then show. It's just for the reloading of the members page from the initial login which stops it.
any ideas?!
======================
the code to set the session is
if (logindetails.Count > 0) {
System.Data.DataRow details = logindetails[0];
Session["memberLoggedIn"] = true;
}
I then just check if (Convert.ToBoolean(Session["memberLoggedIn"]) == true) on all my pages. To be honest it doesn't seem that reliable and I Think sometimes I need to understand the order in which pages are loaded as when I destroy the session on the log out page, some parts still show the logged in features! (but that's another story....)

try this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var user = HttpContext.Current.User;
if(user.Identity.IsAuthenticated)
{
Session["memberLoggedIn"] = true;
Print();
}
}
}
public void Print()
{
if (Convert.ToBoolean(Session["memberLoggedIn"]) == true)
{
Response.Write("ok");
}
}

This sounds like when you log in you are choosing whether to write "OK" before you have processed the login. In terms of the page's pipeline page_load is before your event handler that you are likely processing the login.
You have various options, the simplest of which could be to move this particular logic to Page_PreRender (if it makes sense to) as at this point your session variable will have been set.

Related

ASP.NET const string session key lost on PostBack

My session key is a const string variable. See below.
On first Page Load, I add a string to the session using this key. I also indicate to KeepAlive on the key on the first load and every PostBack. However, on PostBack, I notice that the key is no longer in the session.
I found that to fix this, I simply have to remove "const" from the variable, and everything works fine.
Can someone explain and provide any educational resources on why this is happening.
private const string ENTITY_KEY = "c335a928-72ac-4403-b5f8-418f1e5ac1ec";
public string CurrentEntity
{
get { WebClientSession.Current[ENTITY_KEY] as string); }
set { WebClientSession.Current.AddTransient(ENTITY_KEY, value); }
}
protected void Page_Load(object sender, System.EventArgs e)
{
string key = (string)Request["Id"] + "";
CurrentEntity = Mapper.Lookup.FindById(key);
WebClientSession.Current.KeepAlive(ENTITY_KEY);
}
private void _bindGrid()
{
...
// CurrentEntity is null here on PostBack. Good on first load.
...
}
I am not sure what WebClientSession is but the HttpSessionState will work with const. There is no reason why it should not work. Here is the proof that it will work:
private const string ENTITY_KEY = "c335a928-72ac-4403-b5f8-418f1e5ac1ec";
protected void Page_Load(object sender, EventArgs e) {
if( !this.IsPostBack ) {
Session.Add( "ENTITY_KEY", ENTITY_KEY );
}
}
protected void Button1_Click(object sender, EventArgs e) {
string s = Session[ "ENTITY_KEY" ].ToString();
}
I simply added a button to my form. In the load method if the page is being requested I added a const variable's contents to the Session. In the click handler of the button, which is the form being posted, I access it from the Session and it is there.
So why is it not working for you?
There are 2 possible reasons:
Reason 1
The issue is in your WebClientSession class. I do not know the details of that class so cannot say what the issue is.
Reason 2
Session is stored in memory on the server. So, if this site is deployed on a farm, it is possible that the server which served the page initially added the ENTITY_KEY to Session. But when the page is posted back on the button click, another server serves the request. This server may not have the ENTITY_KEY in its memory since it is possible it has never served that page yet. In a web farm, you would want to use another source to store session related data such as a database or a file etc.

How to programmatically fail Page validation in button click?

In my button click, I would like to cause the page validation to fail if it meets a certain criteria. The problem is that that Page.IsValid is read-only.
This is what I am trying in my button click:
protected override void CreateChildControls()
{
base.CreateChildControls(container);
MyBtn += MyBtn_Click;
MyBtn += MyBtn_Click2; // Cannot move this
}
protected void MyBtn_Click(object sender, System.EventArgs e)
{
CaptchaControl.Validate();
if (!CaptchaControl.IsValid)
{
Page.IsValid = false; // Error because read-only
// Stop before running MyBtn_Click2!
}
}
If my captcha fails validation, I want to return to the page immediately, before it starts running the 2nd click event. Any ideas on how to do this?
I would personally use a hidden field and mark it as required. Put a default value in it, and if your captcha fails, remove the value and revalidate the page.
if (!CaptchaControl.IsValid)
{
myHiddenField.Value = null;
Page.Validate();
}
If your myBtn2 control is using if (Page.IsValid) to execute code, the hidden required field should be empty and now invalid.

Redirect after login in site

i use asp login control in web application (ASP.NET 4). if user in admin role i want redirect to admin page.
i use this code, but not working:
protected void baseLogin1_LoggingIn(object sender, LoginCancelEventArgs e)
{
if (Page.User.Identity.IsAuthenticated && Roles.IsUserInRole(Page.User.Identity.Name, "Admin"))
{
Page.Response.Redirect("admin/Default.aspx");
}
}
please help me.
LoggingInEvent is raised before the user is authenticated. So the first part of your condition is always false. Move you logics under LoggedIn event.
Try this one:
protected void baseLogin1_LoggedIn(object sender, EventArgs e)
{
if (Context.User.Identity.IsAuthenticated && Context.User.IsInRole("Admin"))
{
Context.Response.Redirect("admin/Default.aspx");
}
}
Use the LoggedIn event: Event description is here
You should really be using Server.Transfer("~/admin/Default.aspx"); as it is a little more efficient (less round trips).
If the page needs to preserve the query string for a bookmark or it is important to preseve the correct URL in the browser then Response.Redirect() is needed but be aware of the extra bandwidth cost.

Silverlight callback mystery behavior

I am writting this method to track if changes occured on a page so the user can trigger a reload of a dependent system. So this as you can see triggers when the user is trying to navigate away from the page. If the e.Cancel is not there the behavior seems fine the async web-service call happen as expected but I am not sure what is really happening in the back.
The reload button click method triggers a chain of event that usually update the display but since the user has navigated away from the page the components are no longer visible. Can this cause problems to the application? Should I be forcing the user to remain on the same page just to prevent possible callback problems?
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
if (hasDataBeenModified)
{
if (System.Windows.Browser.HtmlPage.Window.Confirm("You have not reloaded the policies\nDo you want to do it now?"))
{
//e.Cancel = true;
ReloadButton_Click(null, null);
}
}
}
Instead of using OnNavigatingFrom, use OnBackKeyPress
protected override void OnBackKeyPress(CancelEventArgs e)
{
if (hasDataBeenModified)
{
if (System.Windows.Browser.HtmlPage.Window.Confirm("You have not reloaded the policies\nDo you want to do it now?"))
{
e.Cancel = true;
ReloadButton_Click(null, null);
}
}
}

How to use the onClick event for Hyperlink using C# code?

I am trying to add a condition for a hyperlink that I have in my page.
Instead of just using a particular link like: Tutorial I want to display different pages for different users. For example, if the user is logged in as Admin, they will be presented with different link than regular users.
I have modified my hyperlink as: <a onclick="displayTutorial_Click">Tutorial</a>
and added this code:
protected void displayTutorial_Click(object sender, EventArgs e)
{
// figure out user information
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
System.Diagnostics.Process.Start("help/AdminTutorial.html");
else
System.Diagnostics.Process.Start("help/UserTutorial.html");
}
But this didn't work. Can anyone please help me to figure out how I can make the Tutorial link work properly? Thank you a lot in advance!!!
The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)
What you want is a server-side control, like the LinkButton:
<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>
This has an OnClick attribute that will call the method in your code behind.
Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.
protected void Page_Load(object sender, EventArgs e)
{
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Really, it would be best to check that you actually have a user first.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Wow, you have a huge misunderstanding how asp.net works.
This line of code
System.Diagnostics.Process.Start("help/AdminTutorial.html");
Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.
A very easy solution would be to change the href attribute of the link in you page_load method.
Your aspx code:
Tutorial
Your codebehind / cs code of page_load:
...
if (userinfo.user == "Admin")
{
myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else
{
myLink.Attributes["href"] = "help/otherSite.html";
}
...
Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.
this may help you.
In .cs page,
//Declare a string
public string usertypeurl = "";
//check who is the user
//place your code to check who is the user
//if it is admin
usertypeurl = "help/AdminTutorial.html";
//if it is other
usertypeurl = "help/UserTutorial.html";
In .aspx age pass this variabe
<a href='<%=usertypeurl%>'>Tutorial</a>

Categories

Resources