在WebApi Core ActionFilter中获取Request Body as String?

时间:2017-11-22 07:27:34

标签: asp.net-web-api asp.net-core asp.net-core-webapi .net-core-2.0

以下是WebApi .Net Core 2项目中的ActionFilter:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequestLoggingAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        var request = actionContext.HttpContext.Request;
        var route = request.Path.HasValue ? request.Path.Value : "";
        var requestHeader = request.Headers.Aggregate("", (current, header) => current + $"{header.Key}: {header.Value}{Environment.NewLine}");
        request.EnableRewind();
        var requestBody = new StreamReader(request.Body).ReadToEnd();
    }
}

requestHeader具有正确的价值且没有问题,但requestBody始终为空。
我通过发送具有以下正文的请求来测试它。

[
 {
  "TrackingCode": "96003445",
  "Description": "",
  "InnerMessage": "",
  "Status": 11
 },
 {
  "TrackingCode": "96003840",
  "Description": "",
  "InnerMessage": "Inner message",
  "Status": 11
 }
]

如何在WebApi Core 2 ActionFilter中获取请求正文?

1 个答案:

答案 0 :(得分:1)

使用@Nkosi指南,我可以找到以下解决方案:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequestLoggingAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        var request = actionContext.HttpContext.Request;
        var route = request.Path.HasValue ? request.Path.Value : "";
        var requestHeader = request.Headers.Aggregate("", (current, header) => current + $"{header.Key}: {header.Value}{Environment.NewLine}");
        var requestBody = "";
        request.EnableRewind();
        using (var stream = new StreamReader(request.Body))
        {
            stream.BaseStream.Position = 0;
            requestBody = stream.ReadToEnd();
        }
    }
}

工作正常