Is there a possible way to disable Cache Interceptors while on development, except for putting minimum TTL for a cache?
#UseInterceptors(CacheInterceptor)
as a global, so the developer wont have to wait until the cache is cleared during development.
You can try this:
#UseInterceptors(process.env.NODE_ENV === "development" ? function() {} : CacheInterceptor)
Basically, use a dummy interceptor during development so that data won't be cached
Related
I am using "caches" to cache in service worker my PWA assets and make it available offline.
When I change an asset, specifically a js file, I modify at least one byte in my service worker to trigger its native update: the service worker updates and retrieves all of its previously cached assets to refresh its caches.
Yet, server responds with a cached version of the file, and whereas I own the files served I have no control over Cache-Control http header.
How can i prevent browser caching on service worker cached resources? Versioning the files with a
"?v="+version
suffix won't work, because this version cannot be passed to the or or tags that references the cached files in html files, which are static and caches will not recognize and serve offline unversioned file names.
Since "caches.addAll" does not allow AFAIK any means to specify http request headers such as Cache-Control as fetch or XMLHttpRequest do, how can I prevent additional aggressive caching stages over my assets?
I am using plain Javascript and if possible I need it to be done without any additional library. Note also that meta http-equiv tags won't solve the problem for assets other than complete html.
You can bypass the browser's cache by explicitly constructing a Request object with a cache property set to an appropriate cache mode. 'reload' is a good choice, as it will bypass the browser's cache for the outgoing request, but it will update the browser's cache with the response (so you'll have a fresher browser cache overall). If you don't even want that update to be performed, you could use 'no-store'.
Here's some code showing how to do this concisely for an array of URLs that could be passed in to cache.addAll():
async function addAllBypassCache(cacheName, urls) {
const cache = await caches.open(cacheName);
const requests = urls.map((url) => new Request(url, {
cache: 'reload',
}));
await cache.addAll(requests);
}
I enabled the ResponseCaching on my .net Core 2.1 WebApi using the MSDN Documentation:
https://learn.microsoft.com/en-us/aspnet/core/performance/caching/middleware?view=aspnetcore-2.1
It works correctly.
Now I want after an update, clear the cache globally.
Innocently, I thought using:
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
will clear automatically the cache but it s not the case.
How can I do that?
Thanks for your help
There really is nothing to “clear” in your case because this is cached on the client via headers in the response.
I think you are looking for something more of a data store like Redis to cache this response data. The way you are doing it now the browser will cache locally and there is no way for you to invalidate that on the client
I am trying to configure sessions for an asp.net core 2.0 website, but the session cookie is never set.
I call ..
app.UseSession();
...in Startup.Configure and ...
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.HttpOnly = false;
options.Cookie.Name = "WS_AUTH_ID";
});
... in the ConfigureServices method.
In the Controller I can acess ...
HttpContext.Session.Id;
... but the id is always different for every request.
Am I missing something?
Update: I should metion that I can set cookies "manually" and the browser will "receive" them.
HttpContext.Response.Cookies.Append("Test_cookie", "yo");
This was the cause for me:
The extension Microsoft.AspNetCore.CookiePolicy (UseCookiePolicy) was blocking the session cookie. Removing this extension and running the app in a new browser window fixed the issue.
Rationale: this extension blocks the cookies sent to the browser until the user accepts them. Since the session key is stored in a cookie and cookies are blocked by this extension... No cookies, no session.
Another workaround could be to enable the application to work without session until the user accepts cookies (I didn't test this workaround).
Hope that helps.
If you have the cookie policy turned ON the session cookiewon't be created until the user accepts the use of Cookies, this is to comply with the EU's GDPR.
You can remove the line
app.UseCookiePolicy();
from you Startup and then it will work, otherwise your users will need to agree to the use of cookies before you can use the cookie for session control.
For me the problem was solved by one of the comments on the question:
The cookie isn't written unless you add something to the session.
So just requesting the Session.Id won't help, you actually have to set something.
In my case it was a variable that was only set after some condition, and before that condition was met, it would create a new session ID over and over again.
You have to type the following in your ConfigureServices method:
services.AddMvc()
.AddSessionStateTempDataProvider();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.Name = ".MyApplication";
});
In your Configure type the following
//enable session before MVC
app.UseSession();
app.UseMvc();
I am developing a rest api that serves a game. Every three minutes a job runs on server updating an important information of this game. So after this job runs, I need to invalid the cache and create a new one with recent information.
Ok, I implemented on my application MemCached, but a senior developer said that it would be very important to have other cache. He suggested to me to use Varnish, but I really don't know if it would fit in my logic.
Do you have any suggestions of how I could achieve this?
Varnish will work just fine in your case. Of course, Memcached is used for caching transient data whereas Varnish is a full page cache, so it's great for reducing the load on your backend application (whichever language it's powered with, PHP or anything).
You will not need to make any change to your application to cache things with Varnish properly (however you could go that route as well, and adjust your app to send the proper caching headers). Simply develop the VCL (Varnish Configuration Language) file with instructions on your cache policy.
Do not use complete copy paste for VCL files you find online. Add smallest snippest as possible, understand how things work and Varnish will not dissapoint you. Important would be:
Ensure that your cache varies by the API token (if you use for API authentication). You will implement this in vcl_hash procedure.
Integrate cache clearing in your job for updating information: Varnish cache can be cleared by use of a PURGE HTTP request (again, you'd need to develop the necessary VCL code for it, inside vcl_recv procedure).
You can use Mcrouter a memcached protocol router to basically replicate your Memcache.
This config can handle your request:
{
"pools": {
"A": {
"servers": [
// First Memcache address:
"memcache_1_ip:11211",
// Second Memcache address:
"memcache_2_ip:11211"
]
}
},
"route": {
"type": "OperationSelectorRoute",
"operation_policies": {
"add": "AllSyncRoute|Pool|A",
"delete": "AllSyncRoute|Pool|A",
"get": "LatestRoute|Pool|A",
"set": "AllSyncRoute|Pool|A"
}
}
I'm using the jQuery .get() function to load in a template file and then display the loaded HTML into a part of the page by targeting a particular DOM element. It works well but I've recently realised for reasons that confound me that it is caching my template files and masking changes I have made.
Don't get me wrong ... I like caching as much as the next guy. I want it to cache when there's no timestamp difference between the client's cache and the file on the server. However, that's not what is happening. To make it even odder ... using the same function to load the templates ... some template files are loading the updates and others are not (preferring the cached version over recent changes).
Below is the loading function I use.
function LoadTemplateFile ( DOMlocation , templateFile , addEventsFlag ) {
$.get( templateFile , function (data) {
$( DOMlocation ).html(data);
});
}
Any help would be greatly appreciated.
NEW DETAILS:
I've been doing some debugging and now see that the "data" variable that comes back to the success function does have the newer information but for reasons that are not yet clear to me what's inserted into the DOM is an old version. How in heck this would happen has now become my question.
You can set caching to off in the jQuery.get() call. See the jQuery.ajax() doc for details with the cache: false option. The details of how caching works is browser specific so I don't think you can control how it works, just whether it's on or off for any given call.
FYI, when you turn caching off, jQuery bypasses the browser caching by appending a unique timestamp parameter to the end of the URL which makes it not match any previous URL, thus there is no cache hit.
You can probably also control cache lifetime and several other caching parameters on your server which will set various HTTP headers that instruct the browser what types of caching to allow. When developing your app, you probably want caching off entirely. For deployment, I would suggest that you want it on and then when you rev your app, the safest way to deal with caching is to change your URLs slightly so the new versions of your URLs are different. That way, you always get max caching, but also users get new versions immediately.
$get will always cache by default, especially on IE. You will need to manually append a querystring, or use the ajaxSetup method to bust the cache.
As an alternative, I found in the jQuery docs that you can just override the default caching. For me I didn't have to convert all of my $.get over to $.ajax calls. Note that this also overrides default behavior for all other types of calls, like $.getScript which has the opposite default behavior of cache: false from $.get.
https://api.jquery.com/jquery.getscript/
$.ajaxSetup({
cache: false
});