• Net Core 中间件实现修改Action的接收参数及返回值


    新一个WebApi项目(Net Core 2.1)

    新建InputOutputAlterMiddleware类,修改命名空间为Microsoft.AspNetCore.Builder(不修改也没关系,套路而已)
    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;
                //判断是POST提交过来的
                if (method.Equals("POST"))
                {
                    var requestMessage = context.Request.Form["RequestMessage"];
                    _logger.LogInformation("requestMessage:" + requestMessage);
    
                    var alterValue =$"{requestMessage}被我修改啦!";
                    var dic = new Dictionary<string, StringValues>
                    {
                        { "value", new StringValues(alterValue) }
                    };
                    //修改提交过来的值
                    context.Request.Form = new FormCollection(dic);
                    using (var ms = new MemoryStream())
                    {
                        var orgBodyStream = context.Response.Body;
                        context.Response.Body = ms;
                        context.Response.ContentType = "multipart/form-data";
                        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);
    
    
                        }
                    }
    
                }
                else
                {
                    await _next(context);
                }
    
            }
        }
    
    新建InputOutputAlterMiddlewareExtensions类,修改命名空间Microsoft.AspNetCore.Builder
    public static class InputOutputAlterMiddlewareExtensions
        {
            public static IApplicationBuilder UseInputOutputAlter(
               this IApplicationBuilder builder)
            {
                return builder.UseMiddleware<InputOutputAlterMiddleware>();
            }
    }
    
    在Startup类Configure方法下 添加app.UseInputOutputAlter();
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseInputOutputAlter();
                app.UseMvc();
            }
    
    启动程序 用postman测试,注意Values控制器中的Post的FromBody特性修改成FromForm(只可意会,不可言传)
        // POST api/values
            /// <summary>
            /// 把FromBody修改成了FromForm  因为这里测试是用form提交的
            /// </summary>
            /// <param name="value"></param>
            /// <returns></returns>
            [HttpPost]
            public async Task Post([FromForm] string value)
            {
                await HttpContext.Response.WriteAsync("随便写了 反正你会改的!");
            }
    

    1540279243619

    代码github地址

  • 相关阅读:
    [RxJS] sample
    [Whole Web] SQL INJECTION
    [RxJS] Using iif
    [React] Animate SVG Paths with Framer Motion
    bash 教程5 shell 流程控制 条件判断 重定向 read [MD]
    bash 教程4 shell 脚本 调试 环境 [MD]
    『前端算法』数组合并两个有序数组
    块设备读写测试
    IO栈整体认知
    MySQL [Warning] Can’t create test file xxx lowertest(转)
  • 原文地址:https://www.cnblogs.com/aishangyipiyema/p/9836905.html
Copyright © 2020-2023  润新知