views:

38

answers:

3

Why session is null in this even if i set:

public class HelperClass
{
    public AtuhenticatedUser f_IsAuthenticated(bool _bRedirect)
    {
        HttpContext.Current.Session["yk"] = DAO.context.GetById<AtuhenticatedUser>(1);
        if (HttpContext.Current.Session["yk"] == null)
        {
            if (_bRedirect)
            {
                HttpContext.Current.Response.Redirect(ConfigurationManager.AppSettings["loginPage"] + "?msg=You have to login.");
            }

            return null;
        }

        return (AtuhenticatedUser)HttpContext.Current.Session["yk"];
    }
}

alt text

+1  A: 

Usually session is not available on application authenticate request.

Session will be available after OnAcquireRequestState call. Here is application events call sequence

Also, note that session will be available, only if target HttpHandler implements IRequiresSessionState or IReadOnlySessionState, and AuhenticateRequest is usually called for resources like .js or .jpg.

Valera Kolupaev
A: 

Just throwing this out there. The proper way to reference it is:

System.Web.HttpContext.Current.Session

Or if you've referenced this assembly HttpContext.Current.Session should be good to go.

JonH
Is there any HttpContext not in System.Web namespace?
uzay95
@uzay you do not state how this class was created, could be an external dll. If you just try : Session["Blah"] this won't work. You need to do: System.Web.HttpContext.Current.Session["blah"]. Or create a wrapper class that wraps all session variables.
JonH
You are right if i call with only Session["blah"] . I'm calling it in aspx.cs class top of methods. Thats why Session is always coming null. ( I think...! )
uzay95
A: 

When i call the method with this code i'm getting error:

public partial class AddNews : System.Web.UI.Page
{
    private AtuhenticatedUser yk = (new HelperClass()).f_IsAuthenticated(true);
    protected void Page_Load(object sender, EventArgs e)
    {
        //
    }

But when i call the method in Page_Load function it is working

public partial class AddNews : System.Web.UI.Page
{
    private AtuhenticatedUser yk =new AtuhenticatedUser();
    protected void Page_Load(object sender, EventArgs e)
    {
        yk = (new HelperClass()).f_IsAuthenticated(true);
    }

I think Valera Kolupaev is right ;)

uzay95