ASP.NET CORE 自定义中间件

举报
Echo_Wish 发表于 2022/07/04 09:32:40 2022/07/04
【摘要】 ASP.NET CORE 自定义中间件

ASP.NET CORE 自定义中间件

一般是两种方式,
通过lambda表达式,直接在startup类中的configure中书写。

// 通过查询字符串设置当前请求的区域性
app.Use(async (context, next) =>
        {
            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
            await next();
        });

或者是使用C#类。

    // 自定义中间件类
    public class MyCustomMiddleWare
    {
        // 字段,只读
        private readonly RequestDelegate _next;
        // 必须有一个 RequestDelegate 类型参数的公共构造函数
        public MyCustomMiddleWare(RequestDelegate next)
        {
            _next = next;
        }
        // 必须有一个 Invoke或InvokeAsync 方法,返回Task,接受第一个为HTTPcontext的参数
        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;
            }
            // 将请求传递回管道
            // Call the next delegate/middleware in the pipeline
            await _next(context);
        }
    }
    // 扩展方法必须在非泛型静态类型中定义
    public static class MyCustomMiddleWareExtensions
    {
        // 静态方法,公开中间件
        public static IApplicationBuilder UseMyCustom(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyCustomMiddleWare>();
        }
    }

最后在startup的configure中注册中间件
app.UseMyCustom();

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200