Share via


Unable to retieve the request from HttpActionContext

Question

Tuesday, August 22, 2017 2:29 AM

Hello,

I have written a custom Filter derived from ActionFilterAttribute.

public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string rawRequest;
            using (var stream = new StreamReader(actionContext.Request.Content.ReadAsStreamAsync().Result))
            {
                stream.BaseStream.Position = 0;
                rawRequest = stream.ReadToEnd();
            }
        }

However I am unable to retrieve the content, which is of StreamReader type and is always coming as blank despite all the attempts. I am unable to set the position since the stream is not seekable. Any help would be greatly appreciated.

All replies (1)

Wednesday, August 23, 2017 3:06 AM

Hi puneetjain,

The request body is a non-rewindable stream, it can be read only once. The formatter has already read the stream and populated the model. We're not able to read the stream again in the action filter.

For a workaround, I suggest you try below code:

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            using (var stream = new MemoryStream())
            {
                var context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];
                context.Request.InputStream.Seek(0, SeekOrigin.Begin);
                context.Request.InputStream.CopyTo(stream);
                string requestBody = Encoding.UTF8.GetString(stream.ToArray());
            }           
            base.OnActionExecuting(actionContext);
        }

# Web Api Request Content is empty in action filter

https://stackoverflow.com/questions/21351617/web-api-request-content-is-empty-in-action-filter

Best Regards,

Edward