Search code examples
asp.net-web-api2action-filter

Sniff request in ActionFilter


One parameter in a Web API method is unexpectedly null, so I want to inspect the request. In support of this I wrote an ActionFilterAttribute and implemented the OnActionExecuting method. Attempting to retrieve Content as per the code below returns an empty string, but ContentLength says content is 345 bytes and content type is JSON (as expected).

using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Website.ActionFilters
{
  public class ActionFilterSniffAttribute : ActionFilterAttribute
  {
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
      Task<string> task = actionContext.Request.Content.ReadAsStringAsync();
      while (task.Status != TaskStatus.RanToCompletion)
        Thread.Sleep(10);
      Debug.WriteLine(task.Result);
    }
  }
}

What is the correct way to get hold of the HTTP request string? Installing Fiddler on the server is not something I'm keen to do.


Solution

  • This mechanism worked for me and is a good explanation of what is occurring.

    Web API action filter content can't be read

    public override async void OnActionExecuting(HttpActionContext actionContext)
        {
            System.Net.Http.HttpRequestMessage request = actionContext.Request;
            Stream reqStream = await request.Content.ReadAsStreamAsync();
    
            if (reqStream.CanSeek)
            {
                reqStream.Position = 0;
            }
    
            //now try to read the content as string
            string data = await request.Content.ReadAsStringAsync();
            Debugger.Break();
        }