.net core獲取http請求中body的數據


很多人可能會這樣寫:

[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,能正確獲取到數據了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM