简体   繁体   English

.NET Core 中的 HttpContext 和缓存 >= 1.0

[英]HttpContext and Caching in .NET Core >= 1.0

I am trying to port some libraries from the old MVC5 System.Web based stack to .Net Core.我正在尝试将一些库从旧的基于 MVC5 System.Web 的堆栈移植到 .Net Core。 One issue I am having is the changes in the caching.我遇到的一个问题是缓存的变化。 For example, in MVC5 I was able to read and write i18n related data:例如,在 MVC5 中,我能够读写 i18n 相关数据:

[Code Snippet 1] [代码片段 1]

public static Dictionary<string, IEnumerable<CoreDictionaryResource>> DictionaryResourcesCache {
    get { return (Dictionary<string, IEnumerable<CoreDictionaryResource>>)HttpContext.Current.Cache(string.Concat(_Dictionary, DictionaryID, CultureID)); }
    set { HttpContext.Current.Cache(string.Concat(_Dictionary, DictionaryID, CultureID)) = value; }
}

However, I am reliably informed that System.Web and its HttpContext does not contain a Cache field.但是,我被可靠地告知System.Web及其HttpContext不包含 Cache 字段。 I can see a Current field and then a whole host of fields within this such as Application and Session but alas no Cache .我可以看到一个Current字段,然后是其中的一大堆字段,例如ApplicationSession但可惜没有Cache

I've done the necessary in Startup.cs and the app is configured to use both in memory caching and sessions.我已经在Startup.cs完成了必要的工作,并且该应用程序被配置为在内存缓存和会话中使用。 I know that the sessions work as I have other POCOs cached using我知道会话工作,因为我有其他 POCO 使用缓存

[Code Snippet 2] [代码片段 2]

 return System.Web.HttpContext.Current.Session.GetObject<User>("AuthenticatedUser");

where GetObject in an extension I created.其中GetObject在我创建的扩展中。

Am I barking up the wrong tree trying to use HttpContext to read out from the Cache or perhaps I need to use IDistributedCache as see here, here and on SO .我是不是在尝试使用HttpContext从缓存中读出错误的树,或者我可能需要使用IDistributedCache如此处、 此处SO 上所示

But really I just to port the method within [Code Snippet 1]...但实际上我只是在 [代码片段 1] 中移植该方法......

Any pointer you can give on the new .Net Core with regards to caching would be really helpful.您可以在新的 .Net Core 上提供有关缓存的任何指示都会非常有帮助。

Just FYI I do not want any logic in Controllers, nor in Views.仅供参考,我不想要控制器中的任何逻辑,也不想要视图中的任何逻辑。 The application I am building usings separate DLLs for data access and logic so please don't post any examples with DI into the Controllers.我正在构建的应用程序使用单独的 DLL 进行数据访问和逻辑,因此请不要将任何带有 DI 的示例发布到控制器中。 This issue is more at an infrastrcture level before it hits the MVC stack.这个问题更多地出现在基础设施级别,然后才到达 MVC 堆栈。

Thanks guys and gals.谢谢伙计们和女孩们。

The in memory cache functionality is still there, it has just been moved around a bit.内存缓存功能仍然存在,只是稍微移动了一下。 If you add如果添加

"Microsoft.Extensions.Caching.Memory": "1.1.0"

to you project.json file and the add给你 project.json 文件和添加

        services.AddMemoryCache();

to you Startup.ConfigureServices method, you'll have set up a singleton memory cache instance that works pretty much like the old one did.对于您的 Startup.ConfigureServices 方法,您将设置一个单例内存缓存实例,它的工作方式与旧的非常相似。 You get to it via dependency injection so a controller with a constructor can get a instance.您可以通过依赖注入来获取它,因此带有构造函数的控制器可以获得一个实例。

public class HomeController: Controller 
{
    private IMemoryCache _cache;
    public HomeController(IMemoryCache cache) 
    {
        _cache = cache;
    }

}

You can then use _cache in the class above to get to the globally available singleton class.然后您可以在上面的类中使用 _cache 来访问全局可用的单例类。 There are other sorts of caches that you might want look at as well, including a Redis cache for out of process storage.您可能还需要查看其他类型的缓存,包括用于进程外存储的 Redis 缓存。

You should use the In Memory Cache only as HttpContext cache object was actually appdomain cache object although it is exposed using the HttpContext您应该只使用内存缓存,因为 HttpContext 缓存对象实际上是 appdomain 缓存对象,尽管它是使用 HttpContext 公开的

From the msdn https://msdn.microsoft.com/en-us/library/system.web.httpcontext.cache(v=vs.110).aspx来自 msdn https://msdn.microsoft.com/en-us/library/system.web.httpcontext.cache(v=vs.110).aspx

There is one instance of the Cache class per application domain.每个应用程序域有一个 Cache 类的实例。 As a result, the Cache object that is returned by the Cache property is the Cache object for all requests in the application domain.因此,Cache 属性返回的 Cache 对象就是应用程序域中所有请求的 Cache 对象。

We should use the我们应该使用

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Caching.Memory;
using System;
using Microsoft.Extensions.FileProviders;

namespace CachingQuestion
{
public class Startup
{
    static string CACHE_KEY = "CacheKey";

    public void ConfigureServices(IServiceCollection services)
    {
        //enabling the in memory cache 
        services.AddMemoryCache();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var fileProvider = new PhysicalFileProvider(env.ContentRootPath);

        app.Run(async context =>
        {
            //getting the cache object here
            var cache = context.RequestServices.GetService<IMemoryCache>();
            var greeting = cache.Get(CACHE_KEY) as string;


        });
    }
}

 public class Program
 {
    public static void Main(string[] args)
    {
          var host = new WebHostBuilder()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}
}

My answer is focused on how to port caching implementation from old ASP.Net MVC to ASP.Net CORE the easiest and fastest way possible, and also focusing on not rely on dependency injection.我的答案集中在如何以最简单、最快的方式将缓存实现从旧的 ASP.Net MVC 移植到 ASP.Net CORE,并且还关注不依赖依赖注入。


There is a perfect equivalent of ASP.Net MVC's HttpContext.Current.Cache .有一个完美的等价于 ASP.Net MVC 的HttpContext.Current.Cache Its implementation was intended exactly to permit easy porting between frameworks.它的实现正是为了允许在框架之间轻松移植。 This is:这是:

System.Runtime.Caching/MemoryCache System.Runtime.Caching/MemoryCache
This is pretty much the same as the old day's ASP.Net MVC's HttpRuntime.Cache .这与过去的 ASP.Net MVC 的HttpRuntime.Cache几乎相同。 You can use it on ASP.Net CORE without any dependency injection .您可以在 ASP.Net CORE 上使用它而无需任何依赖注入 This is how to use it:这是如何使用它:

// First install 'System.Runtime.Caching' (NuGet package)

// Add a using
using System.Runtime.Caching;

// To get a value
var myString = MemoryCache.Default["itemCacheKey"];

// To store a value
MemoryCache.Default["itemCacheKey"] = myString;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM