.NET Core 中使用 MemoryCache 缓存

一、Startup类中添加服务

 public void ConfigureServices(IServiceCollection services)
  {
      services.AddMemoryCache();
  }

二、在控制器中使用 IMemoryCache

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiTest.Controllers
{
    [Route("api/MemoryCache")]
    [ApiController]
    public class MemoryCacheController : ControllerBase
    {
        private readonly IMemoryCache _cache;

        public MemoryCacheController(IMemoryCache cache)
        {
            _cache = cache;
        }

        [Route("setmc")]
        [HttpGet]
        public ActionResult<string> Setmc()
        {
            string mc = "hello word! MemoryCache";
            _cache.Set("mc",mc);//设置缓存
            return mc;
        }

        [Route("getmc")]
        [HttpGet]
        public ActionResult<string> Getmc()
        {
            return _cache.Get<string>("mc");//读取缓存
        }
    }
}

原文地址:https://www.cnblogs.com/qingheshiguang/p/14356677.html