Simple way to calculate Response length in MVC4

后端 未结 1 495
渐次进展
渐次进展 2020-12-07 03:16

I was trying to calculate the length of a HTTP Response. Seems the stream doesn\'t want to play. (no read allowed. and the Content-Length doesn\'t seem set) I w

相关标签:
1条回答
  • 2020-12-07 03:43

    You could write a custom Response filter:

    public class ResponseLengthCalculatingStream: MemoryStream
    {
        private readonly Stream responseStream;
        private long responseSize = 0;
        public ResponseLengthCalculatingStream(Stream responseStream)
        {
            this.responseStream = responseStream;
        }
    
        public override void Write(byte[] buffer, int offset, int count)
        {
            this.responseSize += count;
            this.responseStream.Write(buffer, offset, count);
        }
    
        public override void Flush()
        {
            var responseSize = this.responseSize;
            // Here you know the size of the response ...
            base.Flush();
        }
    }
    

    and register it in your Global.asax:

    protected void Application_BeginRequest()
    {
        Context.Response.Filter = new ResponseLengthCalculatingStream(Context.Response.Filter);
    }
    

    And if you wanted to apply this filter only on particular controller actions you could write a custom action filter instead of applying it in the BeginRequest event in Global.asax:

    public class ResponseLengthCapturingAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var response = filterContext.HttpContext.Response;
            response.Filter = new ResponseLengthCalculatingStream(response.Filter);
        }
    }
    

    and then all that's left is decorate the controller action with the corresponding action filter:

    [ResponseLengthCapturing]
    public ActionResult Index()
    {
        ...
        return View();
    }
    
    0 讨论(0)
提交回复
热议问题