ASP.NET MVC Read Raw JSON Post Data

后端 未结 3 2012
醉话见心
醉话见心 2020-12-08 19:30

This is driving me crazy. I\'m using ASP.NET MVC. I have a controller with an HttpPost action that acts as a callback URL that is called by another server (not under my cont

相关标签:
3条回答
  • 2020-12-08 20:02

    Reset the position to Zero before reading the stream. Request.InputStream.Position = 0

    0 讨论(0)
  • 2020-12-08 20:12

    For ASP.NET Core 2,this works for me.

        [HttpPost]
        public ActionResult RawTest() {
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {  
                string content = reader.ReadToEndAsync().Result;
                //...
            }
            //...
        }
    
    0 讨论(0)
  • 2020-12-08 20:17

    Your initial approach should work if you take into consideration the fact, that ASP.NET MVC model binding has already read the stream, so you should rewind it:

    [HttpPost]
    public ActionResult Callback(string secret)
    {
        Request.InputStream.Seek(0, SeekOrigin.Begin);
        string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
    
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题