.net core 6.0添加自定义中间件
什么是中间件?
中间件是嵌入在应用程序管道中的软件,用于处理请求和响应。ASP.net core提供了一组丰富的内置中间件组件,但在某些情况下,您可能需要编写自定义中间件。
让我们看一个实际的例子
了解如何创建自己的自定义中间件并将其添加到ASP.NET Core应用程序的请求管道。
自定义中间件组件与任何其他.NET类一样调用Invoke()方法。但是,构造函数需要她的RequestDelegate类型参数来按顺序执行以下中间件::
visualstudio包括用于创建标准中间件类的模板。为此,右键单击要创建中间件类的项目或文件夹,然后选择添加->新建 项目。这将打开“添加新项目”弹出菜单。在右上角的搜索框中,搜索单词“middleware“如下所示。
选择类并为其命名,然后单击“添加”。
这将如下所示。(使用扩展方法添加中间件类)
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class MyMiddleware {
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) {
_next = next;
}
public Task Invoke(HttpContext httpContext) {
return _next(httpContext);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions {
public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder) {
return builder.UseMiddleware < MyMiddleware > ();
}
}
如上所述,Invoke() 方法不是异步的。因此,将其更改为异步并在调用 next() 之前编写自定义逻辑;
//************ Startup.cs *************
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseMyMiddleware();
app.Run(async (context) => {
await context.Response.WriteAsync("Hello Rajesh Gami!");
});
}
您还可以使用 IApplicationBuilder 的应用程序添加中间件。使用app.UseMiddleware() 方法。
现在你已经学会了在.net core 6.0添加自定义中间件
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!