zoukankan      html  css  js  c++  java
  • 中间件

    核心对象

    • IApplicationBuilder
    • RequestDelegate

    代码演示

                app.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("hello Word");
                });

    指定路径

    代码演示

                app.MapWhen(context =>
                {
                    return context.Request.Query.Keys.Contains("id");
                }, builder =>
                {
                    builder.Use(async (context, next) =>
                    {
                        await context.Response.WriteAsync("hello Word");
                    });
                });

    自定义中间件

    中间件代码

        public class MyMiddleware
        {
            RequestDelegate _next;
    
            public MyMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task InvokeAsync(HttpContext context)
            {
                Console.WriteLine("===========执行前逻辑==========");
                await _next(context);
                Console.WriteLine("===========执行后逻辑==========");
            }
        }

    扩展方法

        public static class MyBuilderExtensions
        {
            public static IApplicationBuilder UserMyMiddleware(this IApplicationBuilder app)
            {
                return app.UseMiddleware<MyMiddleware>();
            }
        }

    Startup类注册中间件

                app.UserMyMiddleware();

    异常处理中间件

    代码演示

                app.UseExceptionHandler(errorApp =>
                {
                    errorApp.Run(async context =>
                    {
                        IExceptionHandlerPathFeature exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                        context.Response.ContentType = "application/json;charset=utf-8;";
                        context.Response.StatusCode = StatusCodes.Status200OK;
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(exceptionHandlerPathFeature));
                    });
                });
  • 相关阅读:
    文字无缝滚动效果,鼠标移入时暂停
    Spring中使用@Autowired注解静态实例对象
    服务器环境搭建
    nexus问题
    useUnicode=true&characterEncoding=UTF-8 的作用
    SpringBoot项目启动时自动执行指定方法
    springboot自定义消息转换器HttpMessageConverter
    kubernetes资源类别介绍
    红黑树与平衡二叉树的比较
    Feign Client的超时时间
  • 原文地址:https://www.cnblogs.com/Lv2014/p/13937562.html
Copyright © 2011-2022 走看看