Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement caching in .NET 6 Development

2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, the editor will show you how to implement caching in .NET 6 development. The knowledge points in this article are introduced in great detail. Friends who feel helpful can browse the content of the article with the editor, hoping to help more friends who want to solve this problem to find the answer to the problem. Let's follow the editor to learn more about "how to implement caching in .NET 6 development".

Demand

Sometimes, in order to reduce the repeated logical execution of client requests for the same resources, we will consider using some caching methods. In .NET 6, we can use the middleware provided by the framework to implement the caching of requested resources.

target

Implement the cache of the request result.

Principles and ideas

For implementing caching in .NET 6, we can use the response caching middleware ResponseCaching, and we can use Marvin.Cache.Headers to provide us with more cache-related properties.

Implementation uses native ResponseCaching to implement caching

Since it is middleware, we introduce it into Program:

Program.cs

/ / omit other... / / configure caching middleware builder.Services.AddResponseCaching (); builder.Services.AddControllers (); / / use caching middleware app.UseResponseCaching (); app.MapControllers ()

In terms of usage, there are several ways to implement configuration: 1) global configuration is applied to all ResponseCache responses with the same ProfileName added; 2) A single Controller/Action is configured and applied to the current Controller/Action;3) after global configuration, a single Controller/Action overrides the global configuration. We will demonstrate the scenarios of 1) and 3).

We are going to demonstrate using the interface that gets all the TodoLists.

Let's take a look at how to configure globally:

Program.cs

/ / omit other... builder.Services.AddControllers (options = > {options.CacheProfiles.Add ("60SecondDuration", new CacheProfile {Duration = 60});})

Verification 1: global configuration Caching

First add attributes to the Action we want to validate:

TodoListController.cs

/ / omit other... [HttpGet] [ResponseCache (CacheProfileName = "60SecondDuration")] public async Task Get () {return ApiResponse.Success (await _ mediator.Send (new GetTodosQuery ();}

Start the Api project and execute the request for TodoLists for the first time:

Request

Response

An additional cache-control field is added in the response header to indicate the type of cache (public) and the expiration time of 60s:

If you sent a request using Postman or Insomia, an additional Age field will be added in the return of the same request before expiration, indicating how many seconds the resource has been cached (Hoppscotch I can't find where to set it, so the following screenshot is from Insomia, if anyone knows anything, you can teach it:

At the same time, if you look at the log, you will find that the second request did not actually execute the SQL statement, which also proves that the return of the second request comes from the cache:

If we send the same request after an interval of more than 60 seconds, we will find something like this in the log:

You can see that the cache has expired, so you need to return the data to the database query and cache the result of this request.

Verification 2: a single Action overrides the global configuration

Let's still use this interface, but modify the properties:

TodoListController.cs

[HttpGet] [ResponseCache (Duration = 120)] public async Task Get () {return ApiResponse.Success (await _ mediator.Send (new GetTodosQuery ();}

Restart the Api project and execute the request to obtain TodoLists for the first time. The request is the same as Verification 1. Let's look at the changes in the response:

Response

You can see that the failure time has changed to 120s, and the others are no longer verified one by one.

Use Marvin.Cache.Headers to achieve more caching functions

Another problem in the cache is that if it is determined that the content of the cached data has changed, you need to get the latest response instead of taking the value directly from the cache. This is done with cache checking, and the most commonly used approach is through Etag. The process of the indication is as follows:

If the resource is requested for the first time, API adds the Etag and Last-Modified fields to the response header:

When the client requests the resource again, because the cache itself does not know whether the resource has been modified, the cache will bring the If-None-Match field (equal to the Etag value received by the client) and the If-Modified-Since field (equal to the Last-Modified value received by the client) to the API side. If the verification finds that the resource has not been modified, then the API side does not need to reacquire the resource, but directly returns the NotModifed field to the cache. Cache returns a value to the client. If the validation discovers that the resource has been modified, API will return a new result.

We add the Nuget package Marvin.Cache.Headers to the Api project to achieve this functionality.

First add services to Program and introduce middleware:

Program.cs

Builder.Services.AddResponseCaching (); builder.Services.AddHttpCacheHeaders (expirationOptions = > {expirationOptions.MaxAge = 180; expirationOptions.CacheLocation = CacheLocation.Private;}, validateOptions = > {validateOptions.MustRevalidate = true;}); / / omit other... app.UseResponseCaching (); app.UseHttpCacheHeaders ()

At the same time, we need to remove the previously added ResponseCache attribute, because the newly introduced library has been done for us, and we can also override the global configuration in the following ways:

[HttpCacheExpiration (CacheLocation = CacheLocation.Public, MaxAge = 60)] [HttpCacheValidation (MustRevalidate = false)]

The override rules are consistent with the rules built into the framework, and I won't continue to demonstrate.

Validation 3: cache check

The request is still to get all the TodoLists:

Response

For the time being, let's just focus on the response head:

If we add a new TodoList before the cache expires, add If-None-Match=53154EEFAE230D733827DBDE49B42AF9 to the request header and execute the fetch request:

You can see that the Etag value has changed within the expiration time, and the check indicates that the resource has changed and needs to be reacquired.

If we get the same resource again, we will get a 304 return:

A little extension

But if we observe and think carefully, we will find that there are two problems with the framework in implementing cache verification:

The If-None-Match header field is manually added to the simulation, which should be done by caching middleware

In the case of response 304, the response body is not actually returned, that is, the unmodified resources in the cache are not returned

These two problems are caused by the ResponseCaching library built into the framework, which can be considered to have not implemented the cache verification mechanism correctly. To this end, we have some alternatives for reference:

Varnish

Apache Traffic Server

Squid

Of course, it is also possible to use a special CDN for caching.

Thank you for your reading, the above is the whole content of "how to implement caching in .NET 6 development". Let's get started. I believe that the editor will certainly bring you better quality articles. Thank you for your support to the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report