Home Backend Development C#.Net Tutorial asp.net core mvc implements pseudo-static function

asp.net core mvc implements pseudo-static function

Feb 20, 2017 pm 05:00 PM

This article mainly introduces the relevant information of asp.net core mvc to implement pseudo-static function in detail. It has certain reference value. Interested friends can refer to it

In large website systems In order to improve system access performance, some infrequent content is often published as static pages, such as the product details page and news details page of the mall. Once this information is published, the frequency of changes will not be very high. If you still use If processed through dynamic output, it will definitely cause a huge waste of resources on the server. But we cannot independently create static pages for these contents, so we can use pseudo-static processing in the system. As for what pseudo-static is, you can search it on Baidu. Let's introduce here how to implement pseudo-static in asp.net core mvc.

In the mvc framework, view represents the view, and the result of its execution is the content ultimately output to the client browser, including html, css, js, etc. If we want to achieve staticization, we need to save the result of view execution as a static file and save it to a specified location, such as disk, distributed cache, etc., so that we can directly read the saved content the next time we access it. No need to execute business logic again. So what should asp.net core mvc do to achieve such a function? The answer is to use filters. In the MVC framework, multiple filter types are provided. Here we are going to use action filters. Action filters provide two time points: before the action is executed and after the action is executed. We can first determine whether the static page has been generated before the action is executed. If it has been generated, we can directly read the file content and output it, and the subsequent logic will be skipped. If there is no production, continue to go down, capture the results at this stage after the action is executed, and then save the static content generated by the results.

Then let’s come to the specific implementation code. First, we define a filter type, which we call StaticFileHandlerFilterAttribute. This class is derived from the ActionFilterAttribute provided in the framework. StaticFileHandlerFilterAttribute overrides the two methods provided by the base class: OnActionExecuted( After the action is executed), OnActionExecuting (before the action is executed), the specific code is as follows:

1

2

3

4

5

6

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false, Inherited = false)]

public class StaticFileHandlerFilterAttribute : ActionFilterAttribute

{

   public override void OnActionExecuted(ActionExecutedContext context){}

   public override void OnActionExecuting(ActionExecutingContext context){}

}

Copy after login

In OnActionExecuting, you need to determine whether the static content has been generated. If it has Generate direct output content, the logic implementation is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

//按照一定的规则生成静态文件的名称,这里是按照area+"-"+controller+"-"+action+key规则生成

string controllerName = context.RouteData.Values["controller"].ToString().ToLower();

string actionName = context.RouteData.Values["action"].ToString().ToLower();

string area = context.RouteData.Values["area"].ToString().ToLower();

//这里的Key默认等于id,当然我们可以配置不同的Key名称

string id = context.RouteData.Values.ContainsKey(Key) ? context.RouteData.Values[Key].ToString() : "";

if (string.IsNullOrEmpty(id) && context.HttpContext.Request.Query.ContainsKey(Key))

{

  id = context.HttpContext.Request.Query[Key];

}

string filePath = Path.Combine(AppContext.BaseDirectory, "wwwroot", area, controllerName + "-" + actionName + (string.IsNullOrEmpty(id) ? "" : ("-" + id)) + ".html");

//判断文件是否存在

if (File.Exists(filePath))

{

  //如果存在,直接读取文件

  using (FileStream fs = File.Open(filePath, FileMode.Open))

  {

    using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))

    {

       //通过contentresult返回文件内容

       ContentResult contentresult = new ContentResult();

       contentresult.Content = sr.ReadToEnd();

       contentresult.ContentType = "text/html";

       context.Result = contentresult;

    }

  }

}

Copy after login

In OnActionExecuted, we need the action result to determine whether the action result type is a ViewResult. If it is through code Execute this result, obtain the result output, and generate a static page according to the same rules as above. The specific implementation is as follows

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

//获取结果

IActionResult actionResult = context.Result;

 //判断结果是否是一个ViewResult

    if (actionResult is ViewResult)

    {

      ViewResult viewResult = actionResult as ViewResult;

      //下面的代码就是执行这个ViewResult,并把结果的html内容放到一个StringBuiler对象中

      var services = context.HttpContext.RequestServices;

      var executor = services.GetRequiredService<ViewResultExecutor>();

      var option = services.GetRequiredService<IOptions<MvcViewOptions>>();

      var result = executor.FindView(context, viewResult);

      result.EnsureSuccessful(originalLocations: null);

      var view = result.View;

      StringBuilder builder = new StringBuilder();

  

      using (var writer = new StringWriter(builder))

      {

        var viewContext = new ViewContext(

          context,

          view,

          viewResult.ViewData,

          viewResult.TempData,

          writer,

          option.Value.HtmlHelperOptions);

  

        view.RenderAsync(viewContext).GetAwaiter().GetResult();

        //这句一定要调用,否则内容就会是空的

        writer.Flush();

      }

      //按照规则生成静态文件名称

      string area = context.RouteData.Values["area"].ToString().ToLower();

      string controllerName = context.RouteData.Values["controller"].ToString().ToLower();

      string actionName = context.RouteData.Values["action"].ToString().ToLower();

      string id = context.RouteData.Values.ContainsKey(Key) ? context.RouteData.Values[Key].ToString() : "";

      if (string.IsNullOrEmpty(id) && context.HttpContext.Request.Query.ContainsKey(Key))

      {

        id = context.HttpContext.Request.Query[Key];

      }

      string devicedir = Path.Combine(AppContext.BaseDirectory, "wwwroot", area);

      if (!Directory.Exists(devicedir))

      {

        Directory.CreateDirectory(devicedir);

      }

  

      //写入文件

      string filePath = Path.Combine(AppContext.BaseDirectory, "wwwroot", area, controllerName + "-" + actionName + (string.IsNullOrEmpty(id) ? "" : ("-" + id)) + ".html");

      using (FileStream fs = File.Open(filePath, FileMode.Create))

      {

        using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))

        {

          sw.Write(builder.ToString());

        }

      }

      //输出当前的结果

      ContentResult contentresult = new ContentResult();

      contentresult.Content = builder.ToString();

      contentresult.ContentType = "text/html";

      context.Result = contentresult;

    }

Copy after login

For the Key mentioned above, we directly add the corresponding Attribute

1

2

3

4

public string Key

{

  get;set;

}

Copy after login

So we can use this filter, the method used: add the [StaticFileHandlerFilter] attribute to the controller or controller method, if If you want to configure different Keys, you can use [StaticFileHandlerFilter(Key="set value")]

Staticization has been implemented, and we still need to consider updates. If an article is updated in the background, we You have to update the static pages. There are many solutions: one is to delete the corresponding static pages synchronously when the content is updated in the background. We introduce another one here, scheduled update, which means that the static page has a certain validity period and is automatically updated after this validity period. To implement this logic, we need to get the creation time of the static page in the OnActionExecuting method, and then compare it with the current time to determine whether it has expired. If it has not expired, the content will be output directly. If it has expired, continue to execute the following logic. The specific code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

//获取文件信息对象

FileInfo fileInfo=new FileInfo(filePath);

//结算时间间隔,如果小于等于两分钟,就直接输出,当然这里的规则可以改

TimeSpan ts = DateTime.Now - fileInfo.CreationTime;

if(ts.TotalMinutes<=2)

{

  using (FileStream fs = File.Open(filePath, FileMode.Open))

  {

    using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))

    {

      ContentResult contentresult = new ContentResult();

      contentresult.Content = sr.ReadToEnd();

      contentresult.ContentType = "text/html";

      context.Result = contentresult;

    }

  }

}

Copy after login

At this point, pseudo-static is achieved. The current processing method can only improve access performance to a certain extent, but it may not be enough for large portal systems. According to the method introduced above, other functional extensions can be carried out. For example, after generating a static page, it can be published to a CDN, or it can be published to a separate content server, etc. Regardless of the method, the implementation idea is the same.

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to asp.net core mvc implementing pseudo-static functions, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use various symbols in C language How to use various symbols in C language Apr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to handle special characters in C language How to handle special characters in C language Apr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

The difference between char and wchar_t in C language The difference between char and wchar_t in C language Apr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

How to convert char in C language How to convert char in C language Apr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

How to use char array in C language How to use char array in C language Apr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

See all articles