getting the request body inside HttpContext from a Middleware in asp.net core 2.0

前端 未结 4 1839
礼貌的吻别
礼貌的吻别 2021-02-20 10:45

I am having a simple middleware which fetches the body of the request and store it in a string. It is reading fine the stream, but the issue is it wont call my controller which

4条回答
  •  后悔当初
    2021-02-20 11:03

    Few things are crucial here:

    • enable buffering
    • last flag leaveOpen in StreamReader
    • reset request body stream position (SeekOrigin.Begin)
    public void UseMyMiddleware(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            context.Request.EnableBuffering();
    
            using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, false, 1024, true))
            {
                var body = await reader.ReadToEndAsync();
    
                context.Request.Body.Seek(0, SeekOrigin.Begin);
            }
    
            await next.Invoke();
        });
    }
    

提交回复
热议问题