.netCore自定义中间件

中间件类

其中的HttpContext 对象包含了请求/响应的数据,操作它就可以获取/修改请求上下文

using Microsoft.AspNetCore.Http;
using System;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;


namespace AEStest
{
     
    public class RequestMiddleware
    {
     
        private readonly RequestDelegate _next;

        public RequestMiddleware(RequestDelegate next)
        {
     
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
     
            try
            {
     
                //请求前操作

                await _next(context);

                //返回前操作
            }
            catch (Exception ex)
            {
     

                throw ex;
            }

        }
    }
}

暴露中间件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;

namespace AEStest
{
     
    public static class RequestMiddlewareExtensions
    {
     
        public static IApplicationBuilder UseRequestMiddleware(
            this IApplicationBuilder builder)
        {
     
            return builder.UseMiddleware<RequestMiddleware>();
        }
    }
}

在Startup类注册中间件

在Configure方法里注册:

app.UseRequestMiddleware();

你可能感兴趣的:(.netCore)