当前位置:网站首页>ASP. Net 6 middleware series - conditional Middleware
ASP. Net 6 middleware series - conditional Middleware
2022-04-23 03:07:00 【Dotnet cross platform】
This article is ASP.NET 6 Middleware family The second part of the article is 4 part .
up to now , We've already introduced it ASP.NET 6 The basics of middleware , Shows how to create a custom middleware class , The importance of middleware execution sequence is discussed .
In the last part of this series , We will show two ways to conditionally execute Middleware in a pipeline :
use AppSettings.json Settings in file , To determine whether to add middleware to the pipeline ;
By using the data of the incoming request , Conditionally execute the middleware already in the pipeline .

be based on AppSettings Conditional Middleware
Let's review , In the last article TimeLoggingMiddleware class :
using MiddlewareNET6Demo.Logging;
using System.Diagnostics;
namespace MiddlewareNET6Demo.Middleware
{
public class TimeLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILoggingService _logger;
public TimeLoggingMiddleware(RequestDelegate next,
ILoggingService logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
Stopwatch watch = new Stopwatch();
watch.Start();
await _next(context);
watch.Stop();
_logger.Log(LogLevel.Information, "Time to execute: " + watch.ElapsedMilliseconds + " milliseconds.");
}
}
}
Now? , We only hope that under certain conditions ( such as , When we're tracking a BUG, Or the application runs slowly ) Lower bound TimeLoggingMiddleware Add to application pipeline .
In order to conditionally add middleware to the pipeline , We can do it in AppSettings.json Set one in the file, which can be in Program.cs Fields read in .
stay AppSettings.json Add a file named MiddlewareSettings Configuration fields for , And one called UseTimeLoggingMiddleware Configuration item for :
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MiddlewareSettings": {
"UseTimeLoggingMiddleware": "true",
}
}
We also need a class to hold the values of these settings . As agreed , The class name should be the same as the configuration field name MiddlewareSettings matching , The attribute name should be the same as the configuration item name UseTimeLoggingMiddleware matching :
namespace MiddlewareNET6Demo
{
public class MiddlewareSettings
{
public bool UseTimeLoggingMiddleware { get; set; }
}
}
then , stay Program.cs In file , We can read AppSettings.json That part of , And map it to MiddlewareSettings Class :
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddTransient<ILoggingService, LoggingService>();
var app = builder.Build();
var middlewareSettings = builder.Configuration.GetSection("MiddlewareSettings").Get<MiddlewareSettings>();
Only when middlewareSettings Example of UseTimeLoggingMiddleware The property value is true when , Only in this way can we TimeLoggingMiddleware Add to pipe :
//...
if(middlewareSettings.UseTimeLoggingMiddleware)
app.UseTimeLoggingMiddleware();
//...
In this way , According to the settings of the application , To control which middleware is active in the pipeline .
Based on the request URL Conditional Middleware
Another method may be deceptive , Because middleware is always added to the pipeline , But in addition to passing execution to the next middleware , Won't do anything else .
Suppose we have a new middleware class called CultureMiddleware:
using System.Globalization;
namespace MiddlewareNET6Demo.Middleware
{
public class CultureMiddleware
{
private readonly RequestDelegate _next;
public CultureMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var cultureQuery = context.Request.Query["culture"];
if (!string.IsNullOrWhiteSpace(cultureQuery))
{
var culture = new CultureInfo(cultureQuery);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
}
await _next(context);
}
}
}
Please note that , The middleware exists only in incoming requests culture When requesting parameters , Will perform some practical work .
If this parameter exists , The middleware sets the current region of the application to the value of the incoming parameter .
for example , If we submit the following request :
http://codeman.tech/post/123?culture=zh-CN
CultureMiddleware The region of the application is set to zh-CN, Then carry out other normal treatment .
If the incoming request is :
http://codeman.tech/post/123
that , Middleware will do nothing , The area of the application is still the default .
This method of conditionally executing middleware , Than AppSettings.json The solution provides finer grained execution control , But the potential cost is always the need to add middleware to the pipeline .
With TimeLoggingMiddleware For example :
If the incoming request contains a specific value , To perform TimeLoggingMiddleware Code for ;
stay MVC Applications , Maybe we just want to record the execution of a single controller ;
stay Razor Application , Maybe you just want to record the page with the problem ;
stay Web API in , Just one of the endpoints is a little slow .
In these cases , We can all use this method to TimeLoggingMiddleware Locate what we want to record .
版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230301333631.html
边栏推荐
- How to write the expected salary on your resume to double your salary during the interview?
- MYSQL03_ SQL overview, rules and specifications, basic select statements, display table structure
- 利用正反遍历来解决“字符的最短距离”问题
- C# WPF UI框架MahApps切换主题
- tf. keras. layers. Embedding function
- The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details
- 准备一个月去参加ACM,是一种什么体验?
- Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (7)
- be based on. NETCORE development blog project starblog - (1) why do you need to write your own blog?
- Xamarin效果第二十二篇之录音效果
猜你喜欢

Ningde's position in the times is not guaranteed?

Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮

C read / write binary file

Service avalanche effect

Dynamic sequence table + OJ

Small companies don't make formal offers

TP5 customization in extend directory succeeded and failed. Return information

Due to 3 ²+ four ²= five ², Therefore, we call '3,4,5' as the number of Pythagorean shares, and find the array of all Pythagorean shares within n (including n).

Laravel's own paging query

MYSQL04_ Exercises corresponding to arithmetic, logic, bit, operator and operator
随机推荐
Drawing polygons with < polygon / > circular array in SVG tag
tf. keras. layers. MaxPooling? D function
svg标签中利用<polygon/>循环数组绘制多边形
利用正反遍历来解决“字符的最短距离”问题
先中二叉建树
Detailed log display of openfeign call
建立与遍历二叉树
樹莓派開發筆記(十二):入手研華ADVANTECH工控樹莓派UNO-220套件(一):介紹和運行系統
Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
Maui initial experience: Cool
The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details
Laravel's own paging query
Depth deterministic strategy gradient (ddpg)
使用两种方法来解决“最大回文数乘积”问题
[new version release] componentone added Net 6 and blazor platform control support
一套关于 内存对齐 的C#面试题,做错的人很多!
HLS / chisel practice CORDIC high performance computing complex square root
Miniapi of. Net7 (special section): NET7 Preview3
中后二叉建树
How to write the expected salary on your resume to double your salary during the interview?