Question

I have utility class marked as Serializable that I need to store as a session variable. Here is that class:

[Serializable]
    public class NameValuePair<TName, TValue>
    {
        public TName Name { get; set; }
        public TValue Value { get; set; }

        public NameValuePair(TName name, TValue value)
        {
            Name = name;
            Value = value;
        }

        public NameValuePair() { }
    }    

My NancyModule class cannot deserialize the cookie properly, and I get a null Request.Session object.

Here is the progression of how the Session is populated:

LoginModule validates a user, then populates the session:

Request.Session["UserId"] = user.Id;
Request.Session["TimeZoneId"] = user.TimeZoneId;
Request.Session["StandardStartTime"] = user.StandardStartTime;
Request.Session["StandardEndTime"] = user.StandardEndTime;

var nvp = new NameValuePair<string, int>() { Name = "Davie", Value = 777};
Request.Session["NVP"] = nvp;

In a subsequent module the Session object is null. When I remove the nvp object from the Session, deserialization occurs properly and I get my values back. Any insight would be helpful.

Was it helpful?

Solution

Don't store the UserId in the session.

Nancy uses Cookies for sessions, so they are sent to the client, you shouldn't send any sensitive information to the client regardless if the cookie is encrypted or not.

The default implementation for a cookie object serializer is Mono's binary serializer. At a guess, I would assume the serialization of the object creates a cookie that is too large. So maybe the cookie is not being created since its invalid.

Is there any reason why you cannot do this without storing it in session. This data should be able to come from the database easily. If I had a bunch of user settings I would persist the object itself in the database and then just query by ID.

You can argue that "oh but then I need to hit the database on every request", but in my opinion that's not a valid reason. Get by Id is as fast as it gets in a database and even with 100 million records that would return instantly.


Using a base module you could add a pre-hook to query for the user settings and attach them to a property making them accessible to all modules.

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