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));
                    });
                });
  • 相关阅读:
    C# is 与 as 运算符
    C# dynamic类型
    C# 数组
    C# 泛型
    C# 事件
    C# 委托
    C# DateTime类,TimeSpan类
    C# 获取当前应用程序的绝对路径支持asp.net
    C# 父子类_实例_静态成员变量_构造函数的执行顺序
    C# System.Uri类_获取Url的各种属性_文件名_参数_域名_端口等等
  • 原文地址:https://www.cnblogs.com/Lv2014/p/13937562.html
Copyright © 2011-2022 走看看