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

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

问题描述

我正试图捕获原始请求数据以进行问责,并希望将请求正文内容从Request对象中拉出.

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天全站免登陆