How can I read http request body in netcore 3 more than once?

后端 未结 1 1512
别那么骄傲
别那么骄傲 2020-12-11 20:39

I have a netcore 3 API application that logs the incoming request and then passes it on to the controller action.

My code looks like this:

public Req         


        
相关标签:
1条回答
  • 2020-12-11 21:25

    It is a known issue on github.

    A temp workaround is to pull out the body right after the call to EnableBuffering and then rewinding the stream to 0 and not disposing it:

    public class RequestLoggingHandler : AuthorizationHandler<RequestLoggingRequirement>
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        public RequestLoggingHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RequestLoggingRequirement requirement)
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                var request = httpContext.Request;
                request.EnableBuffering();
    
                httpContext.Items["requestId"] = SaveRequest(request);
                context.Succeed(requirement);
    
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private int SaveRequest(HttpRequest request)
        {
            try
            {
                // Allows using several time the stream in ASP.Net Core
                var buffer = new byte[Convert.ToInt32(request.ContentLength)];
                request.Body.ReadAsync(buffer, 0, buffer.Length);
                var requestContent = Encoding.UTF8.GetString(buffer);
                var requestId = _repository.SaveRawHandlerRequest($"{request.Scheme} {request.Host}{request.Path} {request.QueryString} {requestContent}");
    
                request.Body.Position = 0;//rewinding the stream to 0
                return requestId;
            }
            catch (Exception ex)
            {
    
                throw ex;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题