I'm building a website that will have a feature that if you hover over an object, a special div will be filled with ajax with details on the object.
Since the client side isn't really that important, I'll just say that there's jquery hover event on certain elements that trigger ajax .load() with https://api..../GetDetails/*Id* url and that function will fetch the item details via EntityFramework and the View will be something like
@model Details
<h1>@Model.Name</h1>
(again, simplified because it's not the point).
But with the growing userbase, and the fact that a person can just swipe their mouse around like a madman, I figured that not caching this would create a problem with the traffic flow.
Is it possible, and if it is, how can I cache the responses so that
https://api..../GetDetails/ABC always returns the same thing without doing all the math behind and that https://api..../GetDetails/DEF does not return ABC but it's cached as well?
In ASP.NET Core, you can use Response Caching. It will let us add cache related headers to the response. These headers determine how client, proxy or the middleware cache the responses. Refer to the documentation ASP.NET Core Response Caching
It's an extensive feature which can be used to determine the cache location, duration and invalidating cache based on request header values. You can even create cache profiles for different scenarios. Some samples are as below
1.Cache by duration
[ResponseCache(Duration = 60)]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
2.Set the cache location
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
3.Vary the response cache by request header
[ResponseCache(VaryByHeader = "User-Agent", Duration = 30)]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
Create Cache profiles in Startup
services.AddMvc(options =>
{
options.CacheProfiles.Add("Default",
new CacheProfile()
{
Duration = 60
});
options.CacheProfiles.Add("Never",
new CacheProfile()
{
Location = ResponseCacheLocation.None,
NoStore = true
});
});
Use cache profiles as needed
[ResponseCache(CacheProfileName = "Default")]
public IActionResult Index()
{
return View();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With