很多人可能會這樣寫:
[HttpPost] public IActionResult QXQK([FromBody]QXQK qxqk) { Request.EnableBuffering(); Request.Body.Position = 0; StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8); var str = reader.ReadToEndAsync().Result; return Content("qxdm:" + qxqk.qxdm); }
這樣寫的結果就是str為空,但是qxqk.qxdm有值。於是我們把[FromBody]去掉,如下:
[HttpPost] public IActionResult QXQK(QXQK qxqk) { Request.EnableBuffering(); Request.Body.Position = 0; StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8); var str = reader.ReadToEndAsync().Result; return Content("qxdm:" + qxqk.qxdm); }
這樣寫的結果是str能獲取到數據,而qxqk.qxdm為空。最后咱們采用第一種寫法,同時增加中間件,中間件代碼如下:
app.Use(async (context,next) => { if (context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) { context.Request.EnableBuffering(); using (var reader = new StreamReader(context.Request.Body, encoding: Encoding.UTF8 , detectEncodingFromByteOrderMarks: false, leaveOpen: true)) { var body = await reader.ReadToEndAsync(); context.Items.Add("body", body); context.Request.Body.Position = 0; } } await next.Invoke(); });
OK,能正確獲取到數據了。
