views:

366

answers:

2

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.

A: 

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.

womp
Are you mentioning the tight coupling because it's a bad idea? and if so can you elaborate?
Nathan Palmer
Tight coupling is always a bad idea ;) The provider model is meant to be portable, it isn't solely an ASP.Net concept. However, this might not be a concern for your app.
womp
Well, I'm planning on adding IoC so avoiding tight coupling is a core concept there. But this object is a very core part of this website so I'll have to look at way to abstract it out better. Thanks.
Nathan Palmer
If you can add the System.Web.Abstractions.dll from the ASP.Net MVC framework, you could use HttpContextBase instead of HttpContext. If you could then dependency inject the reference, you'd be away to the races.
womp
A: 

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;
        }
    }
}
Adam Carr