Skip to content
mythz edited this page Mar 27, 2013 · 15 revisions

The AuthFeature (plugin) already enables the SessionFeature, but if you want to make use of sessions and don't want to enable the built-in Authentication, you will need to register it manually in your AppHost with:

     public override void Configure(Container container)
     {
         Plugins.Add(new SessionFeature());
     }

When the SesionFeature is enabled, a Global RequestFilter is added to ServiceStack to ensure that all requests have a Temporary ss-id and a Permanent ss-pid session cookies set. These Cookies just contain a unique Base64-encoded Guid. The ss-opt cookie just stores the users preference on whether they want their current session to be temporary or permanent (i.e. to Remember Me or not - Default is Temporary). Permanent session cookie ss-pid will be created even if ss-opt is Temporary - that helps you to link subsequent requests together and can be used for user request analyzing.

If you're interested in the implementation, all the source code for ServiceStack's Sessions are kept in the ISession, SessionFeature, SessionFactory, SessionExtensions and ServiceExtensions classes.

Can be used with any ICacheClient

ServiceStack's implementation of Sessions are clean, in that they work with all of ServiceStack's Caching Providers and are simply pointers to POCOs in your Cache. An example of getting ServiceStack to use an in-memory cache:

container.Register<ICacheClient>(new MemoryCacheClient());

Formatting of Keys used in Cache Providers

For typed or Custom AuthSession the key is:

urn:iauthsession:{sessionId}

When using un-typed Session Bag the key is:

sess:{sessionId}:{key}

The general recommendation is to use typed sessions, which will give you type-safety benefits as well as being able to fetch your entire users session with a single cache call. If you use the dynamic/session bag then it will be a network call for each key accessed - although as caches are designed for fast-access, this isn't too much of a concern.

Using Typed Sessions in ServiceStack

An example of using Typed Sessions is in the Social Bootstrap Api demo where a CustomUserSession is defined as:

public class CustomUserSession : AuthUserSession {
	public string CustomId { get; set; }
}

By inheriting AuthUserSession you're able to keep all the users session together in 1 POCO, which allows you to access everything in 1 cache read or write.

To provide a typed, Convenient API for your service you can add the following to a base class, here's SocialBootstrapApi's AppServiceBase example:

public abstract class AppServiceBase : Service {
	private CustomUserSession userSession;
	protected CustomUserSession UserSession {
		get {
		    return base.SessionAs<CustomUserSession>();
		}
	}
}

This will then enable you to access your users Session in your ServiceStack services with base.UserSession.

Sharing ServiceStack's Typed Sessions in MVC and ASP.NET

ASP.NET's Session Provider model still maintains its old legacy .NET 1.0 roots with it's heavy XML-encumbered config model, it's coupled and un-testable API, and its degrading performance limitations by design makes it difficult for any web service framework to share the same User Sessions with the base ASP.NET Web Forms or MVC web host.

ServiceStack gets around these limitations by providing its own de-coupled, testable and dependency-free ICacheClient and ISession APIs - which all work simply together as they're just plain Guid Session Keys stored in Caches pointing to POCOs.

The method SessionFeature.GetSessionKey allows you to get a Session Key for a current request if you are trying to access it in ASP.NET Web Forms or MVC web host. Using a Session Key you can have a full control over Session object:

// CacheClient is instance of ICacheClient

var sessionKey = SessionFeature.GetSessionKey();

// geting an existing User Session or create a new one 
var userSession = SessionFeature.GetOrCreateSession<AuthUserSession>(CacheClient); 
// or SessionFeature.GetOrCreateSession<CustomUserSession>(CacheClient); 

// modifying User Session
userSession.UserAuthId = model.UserName;

// saving User Session
CacheClient.CacheSet(sessionKey , userSession);

Saving in Service

As a typed session is just a disconnected POCO, it needs to explicitly saved to be persisted - which you can do with the base.SaveSession() Extension method.

Typed Sessions in MVC

To make use of it in MVC, you effectively do the same thing, although this time you can simply inherit the existing ServiceStackController which has the above templated code in a generic MVC Controller Template:

public class ControllerBase : ServiceStackController<CustomUserSession> {}

From there it's just a basic property which you can use in your Controller or assign to your views like this:

public partial class HomeController : ControllerBase {
	public virtual ActionResult Index() {
		ViewBag.Message = "MVC + ServiceStack PowerPack!";
		ViewBag.UserSession = base.UserSession;
		return View();
	}	
}

Typed Sessions in ASP.NET Web Forms

It's the same thing in ASP.NET Web Forms although this comes in the form of a base ASP.NET Web Page which you get for free when you install ServiceStack via the ServiceStack.Host.AspNet NuGet package.

Using Dynamic / Untyped Sessions in ServiceStack

You can access the dynamic UserSession Bag in ServiceStack services via the base.Session property already built-in ServiceStack's ServiceBase base class, e.g:

base.Session["cart"] = new Cart { ... };
var cart = base.Session.Get<Cart>("cart");

Community Resources



  1. Getting Started
    1. Create your first webservice
    2. Your first webservice explained
    3. ServiceStack's new API Design
    4. Designing a REST-ful service with ServiceStack
    5. Example Projects Overview
  2. Reference
    1. Order of Operations
    2. The IoC container
    3. Metadata page
    4. Rest, SOAP & default endpoints
    5. SOAP support
    6. Routing
    7. Service return types
    8. Customize HTTP Responses
    9. Plugins
    10. Validation
    11. Error Handling
    12. Security
  3. Clients
    1. Overview
    2. C# client
    3. Silverlight client
    4. JavaScript client
    5. Dart Client
    6. MQ Clients
  4. Formats
    1. Overview
    2. JSON/JSV and XML
    3. ServiceStack's new HTML5 Report Format
    4. ServiceStack's new CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  5. View Engines 4. Razor & Markdown Razor
    1. Markdown Razor
  6. Hosts
    1. IIS
    2. Self-hosting
    3. Mono
  7. Advanced
    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in caching options
    9. Built-in profiling
    10. Messaging and Redis
    11. Form Hijacking Prevention
    12. Auto-Mapping
    13. HTTP Utils
    14. Virtual File System
    15. Config API
    16. Physical Project Structure
    17. Modularizing Services
  8. Plugins
    1. Sessions
    2. Authentication/authorization
    3. Request logger
    4. Swagger API
  9. Tests
    1. Testing
    2. HowTo write unit/integration tests
  10. Other Languages
    1. FSharp
    2. VB.NET
  11. Use Cases
    1. Single Page Apps
    2. Azure
    3. Logging
    4. Bundling and Minification
    5. NHibernate
  12. Performance
    1. Real world performance
  13. How To
    1. Sending stream to ServiceStack
    2. Setting UserAgent in ServiceStack JsonServiceClient
    3. ServiceStack adding to allowed file extensions
    4. Default web service page how to
  14. Future
    1. Roadmap
Clone this wiki locally