简体   繁体   English

在 ASP.NET Core 中从 ActionExecutionContext 的 HttpContext 中获取 RawBody

[英]Get RawBody from HttpContext of ActionExecutionContext in ASP.NET Core

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.在我的特殊情况下,我选择创建一个基类,覆盖OnActionExecution ,并让我的控制器类从该基类继承。 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);
    }
}

This code takes the mapped view models from the controller method and converts it into JSON (for logging purposes)此代码从控制器方法中获取映射的视图模型并将其转换为 JSON(用于记录目的)

Example Controller methods:示例控制器方法:

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

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

I want to access the raw body of the Request object.我想访问Request对象的原始正文。 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.我找到了多种关于如何读取请求正文流的解决方案,但它们似乎只适用于 .NET Framework 而不适用于 .NET Core。

Question : How can I get the full request body (which includes the original JSON posted against the controller) from ActionExecutinContext in ASP.NET Core?问题:如何从 ASP.NET Core 中的ActionExecutinContext获取完整的请求正文(包括针对控制器发布的原始 JSON)?

You can use EnableBuffering() in .net core 3.x to enable request body for multiple reads :您可以在 .net core 3.x 中使用 EnableBuffering() 为多次读取启用请求正文:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM