Question

I am implementing a custom MembershipProvider in order to pass the login details to a custom business object that we use in several other places in our company. But once we have authenticated I'd like to save this initialized business object in the session to be used later in other pages. Let me give an example.

public override bool ValidateUser(string username,string password)
{
    try
    {
        // I want to keep this "object" in the Session to be used later on
        CustomBusinessObject object = new CustomBusinessObject(username, password);

        return true;
    }
    catch (CustomBusinessAuthenticationException)
    {
        return false;
    }
}

Is there a way for me to do this? I didn't immediately see a way to get access to the Session object through implementing this custom MembershipProvider.

Was it helpful?

Solution

You can access the session by calling System.Web.HttpContext.Current. Just create a custom property on your custom membership provider that checks to see if HttpContext.Current is null and if so, returns null, otherwise access the session value accordingly.

public object CustomObject
{
    get
    {
        if(System.Web.HttpContext.Current == null)
        {
            return null;
        }
        return System.Web.HttpContext.Current.Session["CustomObject"];
    }
    set
    {
        if(System.Web.HttpContext.Current != null)
        {
            System.Web.HttpContext.Current.Session["CustomObject"] = value;
        }
    }
}

OTHER TIPS

You should be able to access System.Web.HttpContext.Current.Session.

Keep in mind that System.Web.HttpContext will be null if your provider is ever used outside of the ASP.Net pipeline, and that by using it inside your provider you will be coupling your provider tightly to ASP.Net.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top