1

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.

Peter Wone
  • 17,965
  • 12
  • 82
  • 134
  • possible repeat http://stackoverflow.com/questions/21351617/web-api-request-content-is-empty-in-action-filter. The issue may be that the content has already been read to supply the action arguments and is forward only read string. – Bill Sep 09 '15 at 19:45
  • Checked your answer below. Works a treat, so the answer to the other question is definitely wrong about the stream being forward only. – Peter Wone Sep 10 '15 at 00:02

1 Answers1

1

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();
    }
Community
  • 1
  • 1
Bill
  • 1,241
  • 17
  • 25