在 ActionFilter 中嗅探请求

Sniff request in ActionFilter

Web API 方法中的一个参数意外为空,因此我想检查请求。为了支持这一点,我写了一个 ActionFilterAttribute 并实现了 OnActionExecuting 方法。尝试按照以下代码检索内容 returns 一个空字符串,但 ContentLength 表示内容为 345 字节且内容类型为 JSON(如预期)。

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);
    }
  }
}

获取HTTP请求字符串的正确方法是什么?我不想在服务器上安装 Fiddler。

这个机制对我有用,很好地解释了正在发生的事情。

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();
    }