An important distinction to know about, is that ServiceStack Sessions are completely independent and are in no way related (except by name) from ASP.NET sessions. For the most part Sessions in ServiceStack are simply blobs stored in the registered Cache provider and referenced with the SessionId Cookies that are sent with each HTTP Request.
The easiest way to access ServiceStack sessions in ASP.NET MVC is to extend the ServiceStackController and use the SessionAs<T>()
method to access your typed session, e.g:
public class MyMvcController : ServiceStackController
{
public ActionResult Index()
{
MyUserSession myServiceStackSession = base.SessionAs<MyUserSession>();
return View();
}
}
This makes use of the registered ICacheClient
provider which is injected in the base.Cache
property. You can use ServiceStack's IOC to autowire ASP.NET MVC controllers with dependencies registered in ServiceStack's IOC by setting MVC's SetControllerFactory()
, e.g:
public override void Configure(Funq.Container container)
{
//Set MVC to use the same Funq IOC as ServiceStack
ControllerBuilder.Current.SetControllerFactory(
new FunqControllerFactory(container));
}
Otherwise if you want to use a different IOC for ASP.NET MVC Controllers and ServiceStack you would need to register the same ICacheClient Provider that's registered in ServiceStack's IOC, in your MVC IOC. If no CacheClient is registered, ServiceStack uses the MemoryCacheClient
by default.
See the wiki for more info about integrating ServiceStack with ASP.NET MVC.
Accessing ASP.NET Request and Session in ServiceStack Services
When hosted on ASP.NET you can access the underlying ASP.NET request with:
public class MyServices : Service
{
public object Any(MyRequest request)
{
var aspReq = base.Request.OriginalRequest as HttpRequestBase;
if (aspReq != null)
{
var value = aspReq.RequestContext.HttpContext.Session["key"];
}
//or if you prefer via the ASP.NET Singleton:
var value = HttpContext.Current.Session["key"];
}
}