本文转自:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state
+
+
+
Session state
+
+
Warning
+
+
+
TempData
+
Cookie-based TempData provider (requires ASP.NET Core 1.1.0 and higher)
+
Copy
C#
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add CookieTempDataProvider after AddMvc and include ViewFeatures.
// using Microsoft.AspNetCore.Mvc.ViewFeatures;
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
}
+
+
Query strings
+
+
Post data and hidden fields
+
Cookies
+
+
HttpContext.Items
+
Cache
+
+
Configuring Session
+
- Add any of the IDistributedCache memory caches. The
IDistributedCacheimplementation is used as a backing store for session. - Call AddSession, which requires NuGet package "Microsoft.AspNetCore.Session".
- Call UseSession.
+
Copy
C#
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.CookieHttpOnly = true;
});
}
public void Configure(IApplicationBuilder app)
{
app.UseSession();
app.UseMvcWithDefaultRoute();
}
}
+
+
+
Loading Session asynchronously
+
+
Implementation Details
+
+
Copy
C#
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.CookieName = ".AdventureWorks.Session";
options.IdleTimeout = TimeSpan.FromSeconds(10);
});
}
+
+
Setting and getting Session values
+
+
Copy
C#
public class HomeController : Controller
{
const string SessionKeyName = "_Name";
const string SessionKeyYearsMember = "_YearsMember";
const string SessionKeyDate = "_Date";
public IActionResult Index()
{
// Requires using Microsoft.AspNetCore.Http;
HttpContext.Session.SetString(SessionKeyName, "Rick");
HttpContext.Session.SetInt32(SessionKeyYearsMember, 3);
return RedirectToAction("SessionNameYears");
}
public IActionResult SessionNameYears()
{
var name = HttpContext.Session.GetString(SessionKeyName);
var yearsMember = HttpContext.Session.GetInt32(SessionKeyYearsMember);
return Content($"Name: \"{name}\", Membership years: \"{yearsMember}\"");
}
+
Copy
C#
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T Get<T>(this ISession session,string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}
+
Copy
C#
public IActionResult SetDate()
{
// Requires you add the Set extension method mentioned in the article.
HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
return RedirectToAction("GetDate");
}
public IActionResult GetDate()
{
// Requires you add the Get extension method mentioned in the article.
var date = HttpContext.Session.Get<DateTime>(SessionKeyDate);
var sessionTime = date.TimeOfDay.ToString();
var currentTime = DateTime.Now.TimeOfDay.ToString();
return Content($"Current time: {currentTime} - "
+ $"session time: {sessionTime}");
}
Working with HttpContext.Items
+
+
Copy
C#
app.Use(async (context, next) =>
{
// perform some verification
context.Items["isVerified"] = true;
await next.Invoke();
});
+
Copy
C#
app.Run(async (context) =>
{
await context.Response.WriteAsync("Verified request? " + context.Items["isVerified"]);
});
+
+
Application state data
+
- Define a service containing the data (for example, a class named
MyAppData).
Copy
C#
public class MyAppData
{
// Declare properties/methods/etc.
}
- Add the service class to
ConfigureServices(for exampleservices.AddSingleton<MyAppData>();. - Consume the data service class in each controller:
Copy
C#
public class MyController : Controller
{
public MyController(MyAppData myService)
{
// Do something with the service (read some data from it,
// store it in a private field/property, etc.
}
}
}
Common errors when working with session
-
"Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'."
Commonly caused by not configuring at least one
IDistributedCacheimplementation. See Working with a Distributed Cache and In memory caching for more information