使用 IMemoryCache
內存中緩存是使用依賴關係注入從應用中引用的服務。 請在ConfigureServices中調用AddMemoryCache()
:html
public class Startup
{
public void ConfigureServices(IServiceCollection services) {
services.AddMemoryCache();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app) {
app.UseMvcWithDefaultRoute();
}
}
在構造函數中請求 IMemoryCache
實例:redis
public class HomeController : Controller
{
private IMemoryCache cache;
public HomeController(IMemoryCache cache) {
this.cache = cache;
}
public IActionResult Index() {
cache.Set("name", $"shijia{DateTime.Now}", TimeSpan.FromSeconds(10));
return View();
}
public IActionResult About() {
object result;
string value = cache.TryGetValue("name", out result) ? $"獲取緩存name{result}" : "獲取緩存失敗";
return Content(value);
}
https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1緩存
要添加對Session支持,不然會報錯Session has not been configured for this
application or request。使用方法 http://www.cnblogs.com/sword-successful/p/6243841.htmlcookie
(1)nuget安裝Microsoft.AspNetCore.Session
(2) ConfigureServices中services.AddSession();
(3)Configure中app.UseSession();
(4)TempData
依賴於Session,因此也要配置Session。
(5)HttpContext.Session,可是原始只有void Set(string key, byte[] value)
、bool TryGetValue(string key, out byte[] value)
這兩個方法。若是using Microsoft.AspNetCore.Http;
(須要安裝Microsoft.AspNetCore.Http.Extensions)還能夠使用SessionExtensions
中的值是int、string類型的,其餘類型只能本身使用json進行序列化處理。
(6)推薦使用redis作進程外session:
http://www.hossambarakat.net/2016/02/03/configuring-redis-as-asp-net-core-1-0-session-store/session
1.在MVC Controller裏使用HttpContext.Sessionapp
using Microsoft.AspNetCore.Http;
public class HomeController:Controller
{
public IActionResult Index() {
HttpContext.Session.SetString("code","123456");
return View();
}
public IActionResult About() {
ViewBag.Code=HttpContext.Session.GetString("code");
return View();
}
}
2.若是不是在Controller裏,你能夠注入IHttpContextAccessorasp.net
public class SomeOtherClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session=> _httpContextAccessor.HttpContext.Session;
public SomeOtherClass(IHttpContextAccessor httpContextAccessor) {
_httpContextAccessor=httpContextAccessor;
}
public void Set() {
_session.SetString("code","123456");
}
public void Get() {
string code = _session.GetString("code");
}
}
資料:ASP.NET Core 中的會話和應用狀態
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1#session-state分佈式
解決方案:
註釋掉下面這段:函數
public void ConfigureServices(IServiceCollection services) {
// services.Configure<CookiePolicyOptions>(options =>
// {
// // This lambda determines whether user consent for non-essential cookies is needed for a given request.
// options.CheckConsentNeeded = context => true;
// options.MinimumSameSitePolicy = SameSiteMode.None;
// });
services.AddMemoryCache();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSession();
}