从ASP.NET Core中的ActionExecutionContext的HttpContext获取RawBody [英] Get RawBody from HttpContext of ActionExecutionContext in ASP.NET Core

查看:465
本文介绍了从ASP.NET Core中的ActionExecutionContext的HttpContext获取RawBody的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类,我想在其中包含所有控制器方法中正在执行的代码.在我的特殊情况下,我选择创建一个基类,覆盖OnActionExecution,并让我的控制器类从该基类继承.效果很好:

I have a base class where I want to include code that is being executed in all of my controller methods. In my special case, I opted for creating a base class, overwriting OnActionExecution, and having my controller classes inherit from that base class. This works quite well:

public class BaseController : Controller
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        string parsedParameters = string.Empty;
        if (context.ActionArguments.Count > 0)
        {
            inputParameters = JsonConvert.SerializeObject(context.ActionArguments.First().Value,
                                    Formatting.None,
                                    new JsonSerializerSettings
                                    {
                                        NullValueHandling = NullValueHandling.Ignore,
                                    });
        }

        // ...

        base.OnActionExecuting(context);
    }
}

此代码从controller方法中获取映射的视图模型,并将其转换为JSON(用于记录)

This code takes the mapped view models from the controller method and converts it into JSON (for logging purposes)

示例控制器方法:

public async Task<IActionResult> Create([FromBody]CreateGroupRequest requestModel)

我当前面临的问题是传递给端点的其他json值不包括在内,因为它们不会被映射(因为视图模型中不存在此类目标属性)

The problem that I currently face is that additional json values that have been passed to the endpoint are not included since they won't be mapped (because such target properties do not exist in the view model)

我想访问Request对象的原始主体.根据我所阅读的内容,如果请求正文流已经被读取一次,则很难访问它.我发现了有关如何读取请求正文流的多种解决方案,但它们似乎仅适用于.NET Framework,而不适用于.NET Core.

I want to access the raw body of the Request object. Based on what I've read, it's difficult to access the request body stream if it was already read once. I found multiple solutions on how read the request body stream but they only seem to work for .NET Framework and not .NET Core.

问题:如何从ASP.NET Core中的ActionExecutinContext获取完整的请求正文(包括针对控制器发布的原始JSON)?

Question: How can I get the full request body (which includes the original JSON posted against the controller) from ActionExecutinContext in ASP.NET Core?

推荐答案

您可以在.net core 3.x中使用EnableBuffering()来启用请求主体的多次读取:

You can use EnableBuffering() in .net core 3.x to enable request body for multiple reads :

var bodyStr = "";
var req = context.HttpContext.Request;
req.EnableBuffering();
req.Body.Position = 0;
using (var stream = new StreamReader(req.Body))
{
    bodyStr = stream.ReadToEnd();
}

这篇关于从ASP.NET Core中的ActionExecutionContext的HttpContext获取RawBody的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆