Asp.net web api 如何在ASP.net Web API控制器中获取响应长度?
在WEBAPI过滤器中,我试图计算响应大小。 类似的过程也适用于MVC控制器 在actionExecutedContext.Response内。我看不到过滤器 所以我尝试了下面的过滤器,但它不起作用 如何获取WEBApi响应的长度? 我可以把它放在Global.ASAX中,它可以工作,但是每次http调用都会被记录下来。。。 因此,API过滤器将是理想的。这里有什么明显的问题吗Asp.net web api 如何在ASP.net Web API控制器中获取响应长度?,asp.net-web-api,Asp.net Web Api,在WEBAPI过滤器中,我试图计算响应大小。 类似的过程也适用于MVC控制器 在actionExecutedContext.Response内。我看不到过滤器 所以我尝试了下面的过滤器,但它不起作用 如何获取WEBApi响应的长度? 我可以把它放在Global.ASAX中,它可以工作,但是每次http调用都会被记录下来。。。 因此,API过滤器将是理想的。这里有什么明显的问题吗 public class BosAPIFilter : System.Web.Http.Filters.ActionF
public class BosAPIFilter : System.Web.Http.Filters.ActionFilterAttribute{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
base.OnActionExecuted(actionExecutedContext);
var httpContext = actionExecutedContext.Request.Properties["MS_HttpContext"] as HttpContextWrapper;
if (httpContext != null) {
actionExecutedContext.Response.
httpContext.Response.Filter = new ResponseStreamHandler(httpContext.Response.Filter);
var handler = httpContext.Response.Filter as ResponseStreamHandler;
var adminService = new AdminServices();
adminService.HttpTrace(httpContext, handler);
}
}
public class ResponseStreamHandler : MemoryStream {
private readonly Stream _responseStream;
public long ResponseSize { get; private set; }
public ResponseStreamHandler(Stream responseStream) {
this._responseStream = responseStream;
ResponseSize = 0;
}
public override void Write(byte[] buffer, int offset, int count) {
this.ResponseSize += count;
this._responseStream.Write(buffer, offset, count);
}
// ReSharper disable once RedundantOverridenMember
public override void Flush() { base.Flush(); }
}
在ASP.NET Web API管道中,操作筛选器在从操作方法返回的结果序列化之前运行。如果查看筛选器中的
actionExecuteContext.Response.Content
,它将是System.Net.Http.ObjectContent
(取决于您的操作方法)。因此,您只能稍后在管道中计算响应大小。您可以使用消息处理程序来执行此操作,但粒度不在操作方法级别。可以获得的最低粒度是路由级别。解决此问题的一种方法是,仅当设置了标志时,才从筛选器在请求字典中设置标志,并从处理程序中记录