首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在WebApi Core ActionFilter中将请求体作为字符串获取吗?

在WebApi Core ActionFilter中将请求体作为字符串获取吗?
EN

Stack Overflow用户
提问于 2017-11-22 07:27:34
回答 1查看 4.7K关注 0票数 0

下面是我在WebApi .Net Core 2项目中的.Net:

代码语言:javascript
运行
复制
[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总是空的。

我用下面的正文向操作发送请求来测试它。

代码语言:javascript
运行
复制
[
 {
  "TrackingCode": "96003445",
  "Description": "",
  "InnerMessage": "",
  "Status": 11
 },
 {
  "TrackingCode": "96003840",
  "Description": "",
  "InnerMessage": "Inner message",
  "Status": 11
 }
]

如何在WebApi核心2 ActionFilter中获得请求体?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-23 03:09:01

有了@Nkosi指南,我可以找到如下解决方案:

代码语言:javascript
运行
复制
[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();
        }
    }
}

它工作得很好

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47429002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档