C# 如何获取HttpRequestMessage数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17971548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:57:13  来源:igfitidea点击:

How to get HttpRequestMessage data

c#asp.net-mvc

提问by user1615362

I have an MVC API controller with the following action.

我有一个具有以下操作的 MVC API 控制器。

I don't understand how to read the actual data/body of the Message?

我不明白如何读取消息的实际数据/正文?

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
}

采纳答案by Mansfield

From this answer:

这个答案

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
    string jsonContent = content.ReadAsStringAsync().Result;
}

Note:As seen in the comments, this code could cause a deadlock and should not be used. See this blog postfor more detail.

注意:如评论中所见,此代码可能导致死锁,不应使用。有关更多详细信息,请参阅此博客文章

回答by Khanh TO

I suggest that you should not do it like this. Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage.

我建议你不要这样做。操作方法应设计为易于单元测试。在这种情况下,您不应该直接从请求中访问数据,因为如果您这样做,当您想对这段代码进行单元测试时,您必须构造一个HttpRequestMessage.

You should do it like this to let MVC do all the model binding for you:

您应该这样做,让 MVC 为您完成所有模型绑定:

[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
        //your logic to process input parameters.

}

In case you do wantto access the request. You just access the Request property of the controller (not through parameters). Like this:

如果您确实想访问请求。您只需访问控制器的 Request 属性(而不是通过参数)。像这样:

[HttpPost]
public void Confirmation()
{
    var content = Request.Content.ReadAsStringAsync().Result;
}

In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.

在 MVC 中,Request 属性实际上是 .NET HttpRequest 的包装器并继承自基类。当你需要单元测试时,你也可以模拟这个对象。

回答by Zebing Lin

  System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
  reader.BaseStream.Position = 0;
  string requestFromPost = reader.ReadToEnd();

回答by codeMonkey

In case you want to cast to a class and not just a string:

如果您想转换为一个类而不仅仅是一个字符串:

YourClass model = await request.Content.ReadAsAsync<YourClass>();