如何使用 .net 4 api 端点从 Request.Content 对象获取原始请求正文 [英] How do I get the raw request body from the Request.Content object using .net 4 api endpoint

查看:19
本文介绍了如何使用 .net 4 api 端点从 Request.Content 对象获取原始请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获原始请求数据以进行问责,并希望从请求对象中提取请求正文内容.

I'm trying to capture the raw request data for accountability and want to pull the request body content out of the Request object.

我已经看到了使用 Request.InputStream 的建议,但该方法在 Request 对象上不可用.

I've seen suggestions doing a Request.InputStream, but this method is not available on the Request object.

知道如何获取 Request.Content 正文的字符串表示吗?

Any idea of how to get a string representation of the Request.Content body?

推荐答案

您可以通过在 Request.Content 属性上调用 ReadAsStringAsAsync 来获取原始数据.

You can get the raw data by calling ReadAsStringAsAsync on the Request.Content property.

string result = await Request.Content.ReadAsStringAsync();

如果你想要一个字节或一个流,有各种重载.由于这些是异步方法,您需要确保您的控制器是异步的:

There are various overloads if you want it in a byte or in a stream. Since these are async-methods you need to make sure your controller is async:

public async Task<IHttpActionResult> GetSomething()
{
    var rawMessage = await Request.Content.ReadAsStringAsync();
    // ...
    return Ok();
}

如果你从这个方法接收到一个空字符串,这意味着其他东西已经读取了它.当它这样做时,它将指针留在最后.执行此操作的另一种方法如下:

if you're receiving an empty string from this method, it means something else has already read it. When it does that, it leaves the pointer at the end. An alternative method of doing this is as follows:

public IHttpActionResult GetSomething()
{
    var reader = new StreamReader(Request.Body);
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var rawMessage = reader.ReadToEnd();

    return Ok();
}

在这种情况下,您的端点不需要是异步的(除非您有其他异步方法)

In this case, your endpoint doesn't need to be async (unless you have other async-methods)

这篇关于如何使用 .net 4 api 端点从 Request.Content 对象获取原始请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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