分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

asp.net core中写入自定义中间件

发布时间:2023-09-06 01:48责任编辑:赖小花关键词:暂无标签

首先要明确什么是中间件?微软官方解释:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?tabs=aspnetcore2x

也就是中,我们需要在整个应用程序的请求管道中注入某一个中间层来做我们想做的事情。谈谈我的理解:
就拿asp.net 的管道模型来说,以往的.net请求管道中我们知道有21个(应该不止)事件来分别处理相应的模块,这是微软为我们设计好的,如果我们需要拓展出来什么,在相应的事件中写入注册就可以了。但是现在的软件设计模型逐渐的加入了一层---中间件,在整个的应用程序请求管道,我们不做任何的事件封装,而是开放出来,由程序猿自己在某个应用程序的某个部分写入自己需要注入的,而且可以注入多个,但是顺序什么的就是由自己定义了。
那么我们就需要基于IApplicationBuilder来构建我们的中间件。在哪个方法里面调用呢?那必须是Configure方法。根据微软官方的解释:Configure 方法用于指定如何响应HTTP 请求。在这里我们需要使用微软的UseMiddleware<T> 拓展方法来构建我们的中间件(每个Use扩展方法将中间件组件添加到请求管道)。我们将中间件封装在类中,并且通过扩展方法公开。封装如下:

public class RequestCultureMiddleware ???{ ???????private readonly RequestDelegate _next; ???????public RequestCultureMiddleware(RequestDelegate next) ???????{ ???????????_next = next; ???????} ???????public 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; ???????????} ???????????// Call the next delegate/middleware in the pipeline ???????????return _next(context); ???????} ???}

接着我们基于IApplicationBuilder接口拓展我们的中间件。通过UseMiddleware 来使用中间件。

public static class RequestCultureMiddlewareExtensions ???{ ???????public static IApplicationBuilder UseRquestCulture(this IApplicationBuilder builder) ???????{ ???????????return builder.UseMiddleware<RequestCultureMiddleware>(); ???????} ???}

最后我们在Configure中使用我们的中间件:

// 自定义中间件.app.UseRquestCulture();

一般来讲,我们是在ConfigureServices 方法中注册服务,然后在Configure 方法中使用,但是
Configgure 方法可使用IApplicationBuilder实例来配置请求管道,不需要再服务容器重注册。当然我们也可以那么做,请参看: https://github.com/aspnet/Docs/tree/master/aspnetcore/fundamentals/startup/sample

asp.net core中写入自定义中间件

原文地址:https://www.cnblogs.com/zhiyong-ITNote/p/8726974.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved