当前位置:网站首页>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
边栏推荐
- 使用split来解决“最常见的单词”问题
- C# 11 对 ref 和 struct 的改进
- 树莓派开发笔记(十二):入手研华ADVANTECH工控树莓派UNO-220套件(一):介绍和运行系统
- If the deep replication of objects is realized through C #?
- Recommend reading | share the trader's book list and ask famous experts for trading advice. The trading is wonderful
- Blazor University (11)组件 — 替换子组件的属性
- 利用栈的回溯来解决“文件的最长绝对路径”问题
- Array and collection types passed by openfeign parameters
- 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客?
- 如果通过 C# 实现对象的深复制 ?
猜你喜欢
Er and eer models
The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details
ASP. Net and ASP NETCORE multi environment configuration comparison
PDH optical transceiver 4-way E1 + 4-way 100M Ethernet 4-way 2m optical transceiver FC single fiber 20km rack type
ASP.NET和ASP.NETCore多环境配置对比
tf. keras. layers. Embedding function
Dynamic sequence table + OJ
最通俗易懂的依赖注入之服务容器与作用域
Onenet connection process
Cherno_ Game engine series tutorial (5): 101~
随机推荐
MySQL port is occupied when building xampp
Use of metagroup object tuple in C
C# 11 对 ref 和 struct 的改进
C read / write binary file
在.NE6 WebApi中使用分布式缓存Redis
Source Generator实战
准备一个月去参加ACM,是一种什么体验?
Middle and rear binary tree
PDH optical transceiver 4-way E1 + 4-way 100M Ethernet 4-way 2m optical transceiver FC single fiber 20km rack type
Impact of AOT and single file release on program performance
Laravel8- use JWT
Use split to solve the "most common words" problem
腾讯视频涨价:一年多赚74亿!关注我领取腾讯VIP会员,周卡低至7元
The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details
利用正反遍历来解决“字符的最短距离”问题
TP5 inherits base and uses the variables in base
Systemctl start Prometheus + grafana environment
微软是如何解决 PC 端程序多开问题的——内部实现
Xamarin effect Chapter 21 expandable floating operation button in GIS
[ncnn] - the meaning of - 23300 in param