Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace SessionExample
public class Startup
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit
public void ConfigureServices(IServiceCollection services)
//retrieve connectoin info from environment variables in this sample
var host = Environment.GetEnvironmentVariable("REDIS_SESSION_SERVICE_HOST");
var port = Environment.GetEnvironmentVariable("REDIS_SESSION_SERVICE_PORT");
var conn = $"{host}:{port}";
var redis = ConnectionMultiplexer.Connect(conn);
.PersistKeysToRedis(redis, "DataProtection-Keys");
services.AddDistributedRedisCache(option =>
option.Configuration = conn;
option.InstanceName = "master";
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
if (env.IsDevelopment())
//This sample is described in
app.Map("/session", subApp =>
subApp.Run(async context =>
// uncomment the following line and delete session coookie to generate an error due to session access after response has begun
// await context.Response.WriteAsync("some content");
RequestEntryCollection collection = GetOrCreateEntries(context);
collection.RecordRequest(context.Request.PathBase + context.Request.Path);
SaveEntries(context, collection);
if (context.Session.GetString("StartTime") == null)
context.Session.SetString("StartTime", DateTime.Now.ToString());
await context.Response.WriteAsync("<html><body>");
await context.Response.WriteAsync($"Counting: You have made {collection.TotalCount()} requests to this application.<br><a href=\"/\">Return</a>");
await context.Response.WriteAsync("</body></html>");
//please add code to confirm session is wokring.
//you can find full code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.