Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8465273
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T14:59:39+00:00 2026-06-10T14:59:39+00:00

I have built a request logging DelegatingHandler using the details in this blog post

  • 0

I have built a request logging DelegatingHandler using the details in this blog post.

I do not want to read the request or response bodies (doubling-up this work seems silly on a potentially high-volume web service); all I want to do is assign each request a unique ID, log the URI and headers; write the request ID to the response in another header and then log the response (Success/fail) and any exception that occurred.

protected override System.Threading.Tasks.Task<HttpResponseMessage> 
  SendAsync(HttpRequestMessage request, 
  System.Threading.CancellationToken cancellationToken)
{
  DateTime receivedUTC = DateTime.UtcNow;

  //I use the Request properties to persist a Request's ID
  var requestID = request.GetRequestUID();
  if (requestID == null)
    requestID = request.SetRequestUID();

  //grab the base response task
  var baseResult = base.SendAsync(request, cancellationToken);

  return baseResult.ContinueWith(innerTask =>
  {
    var tcs = new TaskCompletionSource<HttpResponseMessage>();

    //note I've got rid of SynchronizationContext code out of this
    //to keep it shorter

    //construct the log packet
    LogData toLog = new LogData()
        {
          ReceivedUTC = receivedUTC,
          Request = request,
          RequestID = requestID,
        };

    //get the response
    try
    {
      tcs.SetResult(innerTask.Result);
      //NOTE - If this request actually fails response serialization,
      //       Then the above result will actually look fine, because
      //       The error hasn't occurred yet!
      toLog.Response = innerTask.Result;
      //this adds a header
      AddRequestIDToResponse(toLog.Response, requestID);
    }
    catch (Exception ex)
    {
      tcs.TrySetException(ex);
      toLog.Ex = ex;
    }

    //fire the logging call asynchronously (code elided, just some DB work)
    Task.Factory.StartNew(() => Log(toLog));
    return tcs.Task;
  }).Unwrap();
}

This all works absolutely fine for nearly all requests, except when an exception occurs whilst the ObjectContent returned from an action method gets serialized to the response.

If this happens, the above code has already fired, and the response message it sees in the try/catch block above appears as a normal 200 with the ObjectContent containing the object that will eventually fail serialization. That does makes sense – since serialization to the response body hasn’t occurred yet.

How do I change this code (without forcing a read on the ObjectContent) to ensure that the response message I see is the actual message that the client receives, after content formatting has taken place? Should I be looking at a different extensibility point?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T14:59:41+00:00Added an answer on June 10, 2026 at 2:59 pm

    As a tentative answer until someobody (hopefully) comes along and proves me wrong; it would appear that this is going to be nigh on impossible within the Web API pipeline itself without copying and pasting a huge amount of code.

    The content serialization is triggered at the very top of the Web API pipeline – in the HttpControllerHandler, where the HttpContent is copied to the underlying HttpResponse‘s OutputStream in an internal static method called HttpControllerHandler.ConvertResponse. There aren’t enough extensibility points on the class itself to be able to inject a task in the correct place to be able to log the actual response within the Web API pipeline.

    So I’m faced with:

    • Lifting HttpControllerHandler in it’s entirety from the source
      code and importing it to my project (and all the internals it uses,
      which is not a nice thought), then customising it accordingly.

    • Just force serialization early and catch the exception – I can log
      the exception but not the response. There is one slight issue with
      this, though – writing the request ID to the response is very
      important, and when these formatting exceptions occur, the ID doesn’t
      get written because HttpControllerHandler replaces the entire
      response with it’s error response!

    • Logging requests at the next level up from the Web API. This
      isn’t ideal because I only want Web API requests logged; and
      also the logging code has a dependency on the current request’s
      HttpConfiguration object in order to grab a request-specific DI
      container for resolving database connections (its a multi-tenant web
      service).

    Ultimately the only real option is the last one – to do the work at the IIS or Asp.Net level. So despite all those extensibility points in the Web API – you actually can’t implement a ‘complete’ logging solution within it – that’s really disappointing.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have built a site using php and want to try keep it one
I have built a blog application using Ruby on Rails. In the application I
I have built a test app on android using this cool-ass PhoneGap framework, but
I have built a site using Django and I am receiving this annoying error
I have built a local DVD Database using Codeigniter, With film names etc in.
I have built a mock object using EasyMock, and I'm trying to have the
I have a classic asp application. I want to post a contest form from
We have built some REST (jax-rs) web services using Apache CXF. They return a
I have built a service with ServiceStack (customer example) as per this link: https://docs.google.com/present/view?id=dg3mcfb_213gsvvmmfk
I really hope someone can shed some light on this problem, I have built

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.