Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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:

[Code Snippet 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. I can see a Current field and then a whole host of fields within this such as Application and Session but alas no Cache.

I've done the necessary in Startup.cs and the app is configured to use both in memory caching and sessions. I know that the sessions work as I have other POCOs cached using

[Code Snippet 2]

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

where GetObject in an extension I created.

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.

But really I just to port the method within [Code Snippet 1]...

Any pointer you can give on the new .Net Core with regards to caching would be really helpful.

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. This issue is more at an infrastrcture level before it hits the MVC stack.

Thanks guys and gals.

like image 279
o-o-awake-o-o Avatar asked Dec 13 '16 10:12

o-o-awake-o-o


People also ask

What is HttpContext in .NET Core?

HttpContext encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP request is received. The HttpContext instance is accessible by middleware and app frameworks such as Web API controllers, Razor Pages, SignalR, gRPC, and more.

What are the different caching techniques available in .NET Core?

ASP.NET Core uses two caching techniques. In-memory caching uses the server memory to store cached data locally, and distributed caching distributes the cache across various servers. We'll explore them both below.

What is caching in ASP.NET Core?

Caching makes a copy of data that can be returned much faster than from the source. Apps should be written and tested to never depend on cached data. ASP.NET Core supports several different caches. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the web server.

What is response caching in .NET Core?

Response caching reduces the number of requests a client or proxy makes to a web server. Response caching also reduces the amount of work the web server performs to generate a response. Response caching is controlled by headers that specify how you want client, proxy, and middleware to cache responses.


2 Answers

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

        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. 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. There are other sorts of caches that you might want look at as well, including a Redis cache for out of process storage.

like image 95
GlennSills Avatar answered Sep 30 '22 23:09

GlennSills


You should use the In Memory Cache only as HttpContext cache object was actually appdomain cache object although it is exposed using the HttpContext

From the 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. As a result, the Cache object that is returned by the Cache property is the Cache object for all requests in the application domain.

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();
    }
}
}
like image 30
Rohith Avatar answered Oct 01 '22 00:10

Rohith