使用自宿主OWIN

项目中要做日志过滤器

新建类ApiLogAttribute

继承ActionFilterAttribute

ApiLogAttribute :  ActionFilterAttribute

public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            string result = null;
            Stream stream = actionContext?.Request?.Content?.ReadAsStreamAsync().Result;
            if(stream=null)                return base.OnActionExecutingAsync(actionContext,cancellationToken);
            stream.Position = 0L;             Encoding encoding = Encoding.UTF8;            /* 这个StreamReader不能关闭,也不能dispose 因为你关掉后,后面的管道 或拦截器就没办法读取了 */             var reader = new StreamReader(stream, encoding);             result = reader.ReadToEnd();             /* 这里也要注意: stream.Position = 0;               当你读取完之后必须把stream的位置设为开始                因为request和response读取完以后Position到最后一个位置,交给下一个方法处理的时候就会读不到内容了。             */             stream.Position = 0L;             Console.WriteLine(result);             return base.OnActionExecutingAsync(actionContext, cancellationToken); }

结果发现stream Position 无法设置,CanSeek为false

用 流复制也不管用

MemoryStream stream = new MemoryStream();
Stream.CopyToAsync(stream);
始终读取不到内容

最后读取文档得知 OWIN 中 Request 的content 只能读取一次,已经被解析,无法再次读取

搜索了一番

https://stackoverflow.com/questions/31389781/read-request-body-twice/31395692#31395692

解决办法如下

在Startup中添加添加中间件

这里的流还没有被读取过,直接复制一份CanSeek为false的stream 流 ,进行替换

//Request stream重用
            app.Use(async (context, next) =>
            {
                // Keep the original stream in a separate
                // variable to restore it later if necessary.
                var stream = context.Request.Body;

                // Optimization: don't buffer the request if
                // there was no stream or if it is rewindable.
                if (stream == Stream.Null || stream.CanSeek)
                {

                    await next.Invoke();

                    return;
                }

                try
                {
                    using (var buffer = new MemoryStream())
                    {
                        // Copy the request stream to the memory stream.
                        await stream.CopyToAsync(buffer);

                        // Rewind the memory stream.
                        buffer.Position = 0L;

                        // Replace the request stream by the memory stream.
                        context.Request.Body = buffer;

                        // Invoke the rest of the pipeline.
                        await next.Invoke();
                    }
                }

                finally
                {
                    // Restore the original stream.
                    context.Request.Body = stream;
                }
            });

或者 在过滤器中 通过如下放法 直接 取出已经被解析的参数

/// <summary>
        /// 读取request 的提交内容
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        public string GetRequestValues(HttpActionContext actionContext)
        {
            string result = null;
            foreach (var arg in actionContext.ActionArguments)
            {
                result += $"key={arg.Key};";
                result += $"value={JsonConvert.SerializeObject(arg.Value)};{Environment.NewLine}";
            }

            return result;
        }

Web API Request Content多次读取的更多相关文章

  1. Routing in ASP.NET Web API和配置文件的设定读取

    Routing Tables In ASP.NET Web API, a controller is a class that handles HTTP requests. The public me ...

  2. 【ASP.NET Web API教程】6.3 内容协商

    本文是Web API系列教程的第6.3小节 6.3 Content Negotiation 6.3 内容协商 摘自:http://www.asp.net/web-api/overview/format ...

  3. Asp.Net Web API 2第十六课——Parameter Binding in ASP.NET Web API(参数绑定)

    导航 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html. 本文主要来讲解以下内容: ...

  4. Parameter Binding in ASP.NET Web API(参数绑定)

    Parameter Binding in ASP.NET Web API(参数绑定) 导航 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnbl ...

  5. Web API 方法的返回类型、格式器、过滤器

    一.Action方法的返回类型 a) 操作方法的返回类型有四种:void.简单或复杂类型.HttpResponseMessage类型.IHttpActionResult类型. b) 如果返回类型为vo ...

  6. 浅谈 asp.net core web api

    希望通过本文能够了解如下内容: ControllerBase Attributes Action的返回值类型 ControllerBase 当我们开始实际上项目, 真正实操 anc 时, 肯定会用到 ...

  7. 一张图说明 Web Api 参数绑定默认规则

    请求如下: 控制器如下: 慎重说明:不管请求方式是 get 还是 post , 简单类型的参数,如 name 和 id ,其值都是从 url 里面去取. Web API 从 url 还是 body 获 ...

  8. Dynamics 365本地部署版本配置OAuth 2 Password Grant以调用Web API

    微软动态CRM专家罗勇 ,回复330或者20190504可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me! 根据官方建议,不要再使用Dynamics 365 Custome ...

  9. 温故知新,使用ASP.NET Core创建Web API,永远第一次

    ASP.NET Core简介 ASP.NET Core是一个跨平台的高性能开源框架,用于生成启用云且连接Internet的新式应用. 使用ASP.NET Core,您可以: 生成Web应用和服务.物联 ...

随机推荐

  1. cas单点登录防止登出退出后刷新后退ticket失效报500错

    https://www.cnblogs.com/wangyang108/p/5844447.html

  2. token的设置与获取

    以用户登录为例: application-resources.yml: #用户session在redis中保存的key REDIS_STU_SESSION_KEY: REDIS_USER_SESSIO ...

  3. sqlserver 迁移

    背景 好久没用sqlserver了,好多东西也都记不住了,这次sqlserver同事问了几个问题,也一就回忆下.主要也把sqlserver的迁移过程列下.具体就不多说了. sqlserver 特点是只 ...

  4. selenium——鼠标事件

    右键操作: 双击:

  5. 初学python之路-day04

    每天一篇总结,今天学习的是有关于流程控制的知识. 流程控制,顾名思义,在计算机运行中,程序是被某种控制方式按照某种流程或者规律来执行的.而python程序的运行,肯定也是按照某种规律在执行.这些规律可 ...

  6. 基于BootStrap的initupload()实现Excel上传和获取excel中的数据

    简单说明:后边要做exl解析(还没做呢),所以先有一个excel的的上传以及获取excel中的数据,展示出来. 代码: //html代码 <div class="btn-group&q ...

  7. laravel whereDoesntHave

    select * from `feeds` where not exists (select * from `black_lists` where `feeds`.`user_id` = `black ...

  8. Telephone Lines POJ - 3662 (二分+spfa)

    Farmer John wants to set up a telephone line at his farm. Unfortunately, the phone company is uncoop ...

  9. Ubuntu中eclipse端口被占

    我的eclipse有时候会闪退,然后再次打开运行HTML程序的时候会提示端口被占,即使之前改过端口也会提示,然后我就在网上搜索解决办法,目前亲测有效的是 输入以下命令: lsof -i:8888 // ...

  10. Kali Linux常用服务配置教程DHCP服务原理

    Kali Linux常用服务配置教程DHCP服务原理 动态主机配置协议(Dynamic Host Configuration Protocol,简称DHCP)是一个局域网的网络协议,基于UDP协议工作 ...