.net 5 利用中间件更改接口参数

    public class InputOutputAlterMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public InputOutputAlterMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<InputOutputAlterMiddleware>();
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var method = context.Request.Method;
            if (method.Equals("POST") || method.Equals("GET"))
            {
                var dic = new Dictionary<string, StringValues>();
                foreach (var item in context.Request.Query.Keys)
                {
                    dic.Add(item, new StringValues(context.Request.Query[item].ToString()));
                }

                if (!string.IsNullOrEmpty(context.Request.Path.Value) && context.Request.Path.Value != "/")
                {
                    //对比接口过来的参数,如果参数缺少自动填空 
                    var types = Assembly.GetExecutingAssembly().GetTypes();//可以放入全局配置 不用每次全部加载
                    string[] arr = context.Request.Path.Value.Split('/');
                    var contes = types.Where(m => m.Name == arr[arr.Length - 2] + "Controller").ToList();
                    if (contes.Count > 0)
                    {
                        var action = contes.SelectMany(t => t.GetMethods().Where(a => a.Name == arr[arr.Length - 1])).FirstOrDefault();
                        if (action != null)
                        {
                            var parameters = action.GetParameters();
                            foreach (var item in parameters)
                            {
                                if (!dic.ContainsKey(item.Name))
                                {
                                    dic.Add(item.Name, new StringValues("123456"));
                                }
                            }
                        }
                    }
                }

                //dic.Add("newbarcode", new StringValues("123456"));
                //dic.Remove("barcode");
                //修改提交过来的值
                context.Request.Form = new FormCollection(dic);

                //using (var ms = new MemoryStream())
                //{
                //    var orgBodyStream = context.Response.Body;
                //    context.Response.Body = ms;
                //    context.Response.ContentType = "multi part/form-data;text/html";
                //    await _next(context);

                //    //using (var sr = new StreamReader(ms))
                //    //{
                //    //    ms.Seek(0, SeekOrigin.Begin);
                //    //    //得到Action的返回值
                //    //    var responseJsonResult = sr.ReadToEnd();
                //    //    ms.Seek(0, SeekOrigin.Begin);
                //    //    //如下代码若不注释则会显示Action的返回值 这里做了注释 则清空Action传过来的值  
                //    //    //  await ms.CopyToAsync(orgBodyStream);
                //    //    var alterResult = $"没事返回值【{responseJsonResult}】被我改过来啦!";

                //    //    context.Response.Body = orgBodyStream;
                //    //    //显示修改后的数据 
                //    //    //await context.Response.WriteAsync(alterResult, Encoding.UTF8);

                //    //}
                //}
                await _next(context);

            }
            else
            {
                await _next(context);
            }

        }
    }

    public static class InputOutputAlterMiddlewareExtensions
    {
        public static IApplicationBuilder UseInputOutputAlter(
           this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<InputOutputAlterMiddleware>();
        }
    }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseInputOutputAlter();
}

 

posted @ 2022-04-06 15:15  奉利民  阅读(99)  评论(0编辑  收藏  举报