Modify Request in a MessageHandler?

Topics: Web Api
Aug 31, 2011 at 4:04 AM

Hi there,

Is it possible to intercept an incoming request content, using a MessageHandler?
What I would like to do is to replace the encrypted content with the encrypted content and then let the regular flow take over.
Similar to what can be done with a custom Filter in an IHttpModule to modify the HttpRequest's InputStream.

In pseudo code (will make my intent clearer) it would look something like:


    public class AuthTokenChannel: DelegatingChannel
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            long memberId = 0;
            if (request.Method == HttpMethod.Post)
            {
                 // step 1 do some validation on request
                 bool valid = ValidateRequest(request, out memberId);
                 if (!valid) { return NotAuthorized;}
                 var encryptionKey = GetEncryptionKeyFor(memberId);
 

                // step 2: decrypt content
                var decrypted = DecryptContent(request.Content, encryptionKey);
 

               // step 3: replace content... (THE CRITICAL STEP)
              request.Content = decrypted;
            }
            // store result in case we need to add custom headers
            return base.SendAsync(request, cancellationToken);
        }
   }



Aug 31, 2011 at 9:12 AM

Hi Santiago,

Have you tried this?

request.Content = new StringContent(decrypted /* string */);

or this for binary:

request.Content = new ByteArrayContent(decrypted /* bytes */);

Aug 31, 2011 at 3:14 PM

Absolutely it is possible.  To add to Gerben's list you can also use StreamContent.

Aug 31, 2011 at 3:44 PM

Thanks!
Got it working now!!!

Soooo painless....
I had already started fearing having to deal with Requesr filters at http module level.

Thank you!!!