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地址

转载于:https://www.cnblogs.com/aishangyipiyema/p/9836905.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值