A non-empty request body is required

13,007

The problem ended up being with a bug in a custom middleware I created. I was replaying the request twice.

  public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        string stringBody = string.Empty;
        try
        {
            await next(context).ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            if (context.Request.Body.CanSeek)
            {
                stringBody = await FormatRequest(context.Request).ConfigureAwait(false);
            }
            await HandleExceptionAsync(context, ex, stringBody).ConfigureAwait(false);
        }

        //await next(context).ConfigureAwait(false);
    }

The commented out code was the culprit. If no exception occurred then it would exit the try and essentially replay the same RequestDelegate. My assumption is the request stream has already been read and is already disposed or read to the end.

Share:
13,007
Adrian
Author by

Adrian

Updated on August 06, 2022

Comments

  • Adrian
    Adrian over 1 year

    I've found a few other questions here on SO that address this issue; however, all those questions seem to have had their issues in the type of request being sent wether content-type was the issue, or model binding. In my situation, the error seems to get thrown on the Ok at the end of the action method.

    So far I have have tried the following:

    • Adding/removing FromBody attribute
    • Ensuring my testing framework Swagger is sending as application/json
    • I tried changing to to a Patch just to see what would happen but the issue still persists
    • I also tried changing the return from Ok to NoContent and the issue still persists

    As I said above, I did step through this code and verified that I hit the mapping code and all properties are properly mapped. The user itself does get updated in the database. The error is only thrown after execution exits the action method (after Ok) is called. So this throws me off even more since the error insists my request body is empty.

    Are there any other reasons this error would be thrown besides an actual empty request body or wrong content-type payload?

        /// <summary>
        /// Updates the provided account and setting information
        /// </summary>
        /// <param name="vm"></param>
        [HttpPost]
        [ProducesResponseType(200)]
        [ProducesResponseType(400, Type=typeof(string))]
        public async Task<IActionResult> UpdateAccountInfo([FromBody]UpdateAccountInfoViewModel vm)
        {
            var appModel = _mapper.Map<ChartLog.Application.Models.UpdateAccountInfoModel>(vm);
            appModel.UserId = User.GetUserId().Value;
    
            await _accountApp.UpdateAccountAndSettings(appModel);
            return Ok();
        }