Sey*_*avi 3 c# .net-core asp.net-core
我创建了一个新的 ASP.NET Core Web API 项目。这是ConfigureServices
在 Startup.cs 中:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddMemoryCache();
var serviceProvider = services.BuildServiceProvider();
var cache = serviceProvider.GetService<IMemoryCache>();
cache.Set("key1", "value1");
//_cahce.Count is 1
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我向 IMemoryCache 添加了一个项目。这是我的控制器:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IMemoryCache _cache;
public ValuesController(IMemoryCache cache)
{
_cache = cache;
}
[HttpGet("{key}")]
public ActionResult<string> Get(string key)
{
//_cahce.Count is 0
if(!_cache.TryGetValue(key, out var value))
{
return NotFound($"The value with the {key} is not found");
}
return value + "";
}
}
Run Code Online (Sandbox Code Playgroud)
当我请求时https://localhost:5001/api/values/key1
,缓存为空,并且我收到未找到的响应。
简而言之,您设置值的缓存实例与稍后检索的缓存实例不同。您不能在构建 Web 主机时执行类似操作(即在ConfigureServices
/中Configure
)。如果您需要在启动时执行某些操作,则需要在构建 Web 主机后执行此操作,在Program.cs
:
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
var cache = host.Services.GetRequiredService<IMemoryCache>();
cache.Set("key1", "value1");
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2567 次 |
最近记录: |