如何读取和更改Response的主体到覆盖OnActionExecuted方法的Controller

tru*_*oda 5 c# asp.net-web-api asp.net-core asp.net-core-webapi

我需要为控制器的每个动作的每个JSON答案附加一些信息.为此,我使基本控制器继承自标准MVC Controller类.我试着这样.但我抓住ArgumentException了这样的信息"Stream不可读".当ActionResult对象将数据写入正文时,可能会关闭流.我能做什么?

public override void OnActionExecuted(ActionExecutedContext context)
{
    var respApi = new ResponseApiDTO();
    respApi.Comment = "You could!!!";
    JObject jRespApi = JObject.FromObject(respApi);
    Stream bodyStream = context.HttpContext.Response.Body;
    JObject jbody;

    context.Result = Json(jbody);
    using( var rd = new StreamReader(bodyStream))
    {
        string bodyText = rd.ReadToEnd();
        jbody = (JObject)JsonConvert.DeserializeObject(bodyText);
        jbody.Add(jRespApi);
        context.Result = Json(jbody);
    }
}
Run Code Online (Sandbox Code Playgroud)

tru*_*oda 6

我找到了解决方案.我们需要在管道中执行MVC步骤时将Body流替换为MemoryStream对象.然后我们必须将原始流对象对象返回到Response.Body.

// Extension method used to add the middleware to the HTTP request pipeline.
    public static class BufferedResponseBodyExtensions
    {

        public static IApplicationBuilder UseBufferedResponseBody(this IApplicationBuilder builder)
        {
            return builder.Use(async (context, next) =>
            {
                using (var bufferStream = new MemoryStream())
                {
                    var orgBodyStream = context.Response.Body;
                    context.Response.Body = bufferStream;

                    await next();//there is running MVC

                    bufferStream.Seek(0, SeekOrigin.Begin);
                    await bufferStream.CopyToAsync(orgBodyStream);    
                    context.Response.Body = orgBodyStream;
                }
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后将其包含在pipline中.类启动,方法配置.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {   
           ...
            app.UseBufferedResponseBody();
            app.UseMvc();           
           ...
        }
Run Code Online (Sandbox Code Playgroud)

在替换响应正文流后,您可以通过结果过滤器读取和修改正文内容.

 public class ResultFilterAttribute : Attribute, IResultFilter
    {
        public async void OnResultExecuted(ResultExecutedContext context)
        {
            Stream bodyStream = context.HttpContext.Response.Body;
            bodyStream.Seek(0, SeekOrigin.Begin);
            string bodyText = rd.ReadToEnd();
        }
     }
Run Code Online (Sandbox Code Playgroud)

必须将此属性应用于目标Controller类.