.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,能正确获取到数据了。

posted @ 2020-09-22 18:26  段江涛IT  阅读(4916)  评论(3编辑  收藏  举报
页脚HTML代码