Click here to Skip to main content
15,347,000 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:

I am experimenting with OWIN middleware in an Web API application and I wish to intercept the request in the pipeline and decode the request body in flight before the request gets to the API Controller/Action.

I have taken a json string and base 64 encoded it as part of this test. I am able to intercept the request, read the body text, decode it as to get the original string but I am unable to update the request body with the new data. Here is a code snippet:

public override async Task Invoke(IOwinContext context)
            if (context.Request.ContentType.Equals("text/plain"))
                string body = new StreamReader(context.Request.Body).ReadToEnd();

                byte[] data = Convert.FromBase64String(body);
                string decodedString = Encoding.UTF8.GetString(data);

                context.Request.ContentType = "application/json";
                context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(decodedString));

            await Next.Invoke(context);

This code executes without issue and I can see decoded string value having the correct data. The kicker is that when the request moves on to the controller / action, the body is that of the old data / encoded string.

Has anyone tried to intercept the api request via owin and replace it with something other than what was originally posted?

Sample controller / action snipped used to pull the value from the request body:

// POST api/values
        public void Post([FromBody]string value)
            var req = Request;
            var x = value;

            var y = x;

Thanks in advance!


Updated 19-Oct-18 2:10am

1 solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900