1

I was trying to use Session ("Microsoft.AspNet.Session": "1.0.0-beta5") in asp.net vnext but i cant. I have read many comments like this or this, but everyone seems to be outdated.

I cant use Context.Session.SetInt or Context.Session.SetString; I have only available Context.Session.Set and do not know how to use its object ArraySegment<byte>. Any recommendation?

Community
  • 1
  • 1
ajcarracedo
  • 255
  • 3
  • 13

2 Answers2

1

The ISession interface indeed only has a Set(string key, byte[] value) overload. HttpContext has an ISession Session property.

So everything you want to store in the session has to be converted to a byte array. This can be done in many ways, depending on the type:

byte[] stringBytes = Encoding.UTF8.GetBytes(someString)
byte[] intBytes = BitConverter.GetBytes(someInt);

For complex types, you'll have to use a serializer, for example the BinaryFormatter, as explained in How to convert an object to a byte array in C#.

Luckily there's some extension methods in Microsoft.AspNet.Http that do this for you:

  • SetString(this ISession session, string key, string value)
  • SetInt32(this ISession session, string key, int value)

And of course their respective Get... counterparts that convert the byte array back to the relevant type.

All you need is a using Microsoft.AspNet.Http; directive in your source in order to be able to use these extension methods.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
1

Here you have a really interesting article regarding sessions in asp.net 5 and why it's using a byte array to store sessions ("The main reason behind this decision appears to be to ensure that session values are serialisable for storage on remote servers").

Also keep that in mind that one of the driving forces behind ASP.NET 5 is "cloud-readiness"

http://www.mikesdotnetting.com/article/270/sessions-in-asp-net-5

Vackup
  • 652
  • 4
  • 11