我需要向控制器的每个动作的每个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);
}
}
答案 0 :(得分: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;
}
});
}
}
然后将其包含在pipline中。类启动,方法配置。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseBufferedResponseBody();
app.UseMvc();
...
}
在替换响应正文流后,您可以通过结果过滤器读取和修改正文内容。
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();
}
}
此属性必须适用于目标Controller类。