【问题标题】:Getting the raw Request in ASP.NET MVC在 ASP.NET MVC 中获取原始请求
【发布时间】:2018-10-26 01:22:29
【问题描述】:

我需要获取原始请求字符串。下面是发送到 Controller 的 http 请求示例。实际上,我需要发布数据(最后一行)。我怎样才能得到它?

请注意,我不想使用自动 JSON 模型绑定器。实际上,我需要原始 JSON 文本

POST http://www.anUrl.com/CustomExport/Unscheduled HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://www.anUrl.com/CustomExport
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: localhost:8000
Content-Length: 102
Connection: Keep-Alive
Pragma: no-cache

{"runId":"1","fileDate":"8/20/2012","orderStartMinDate":"10/02/2012","orderStartMaxDate":"10/02/2012"}

最后一行是我需要的。这不进来

var input = new StreamReader(Request.InputStream).ReadToEnd();

【问题讨论】:

    标签: .net asp.net-mvc


    【解决方案1】:

    此时流已经读到最后。需要将 InputStream 的位置设置回开头,才能自己读取。

    Request.InputStream.Position = 0;
    var input = new StreamReader(Request.InputStream).ReadToEnd();
    

    【讨论】:

    • 谢谢,问题就是这样
    【解决方案2】:

    @louis-ricci answear 是正确的,但请记住,如果您在 Action Method 中使用 [FromBody],则在调用 Request.InputStream 时会出现异常,因为 [FromBody] 已经读取请求正文以便通过调用HttpRequest.GetBufferlessInputStream()序列化到模型中,并且该方法不能被调用两次。要解决这个问题,只需不要在您的请求中使用 [FromBody] 并手动将原始请求字符串序列化到您的模型。

    编辑:为了更好地了解该主题的上下文和搜索结果,抛出的错误包含以下消息:

    This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 2010-11-05
      • 2016-11-16
      • 2014-12-26
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      相关资源
      最近更新 更多