0

Introducing JustController:

// many using directives

namespace MyWebApiProject.Controllers
{
    [Route("api/[controller].[action]")]
    [ApiController]
    public class JustController : ControllerBase
    {
        [HttpPost]
        public async Task<ActionResult> GetById(/*Model Class*/ body)
        {
            return StatusCode(/* http status code */, "THIS IS NEEDED VALUE"); // <- Look at this!
        }
    }
}

We also have this middleware:

// many using directives

public class StatusCodeMiddleware
{
    private readonly RequestDelegate _next;

    public StatusCodeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        await _next(httpContext);
        /*
            How to get "THIS IS NEEDED VALUE" from HttpContext here
        */
    }
}

public static class StatusCodeMiddlewareExtensions // For convenient use in Startup.cs
{
    public static void ConfigureCustomStatusCodeMiddleware(this IApplicationBuilder app)
    {
        app.UseMiddleware<StatusCodeMiddleware>();
    }
}

Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.ConfigureCustomStatusCodeMiddleware();

    app.UseRouting();

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}

How do I get "THIS IS NEEDED VALUE" from HttpContext inside the InvokeAsync() method, inside of StatusCodeMiddleware?

Thanks in advance! I really hope the Stack Overflow audience helps me! I googled the solution to this problem for 2 days so I did not find anything. Sorry for my bad English!

  • **Welcome to StackOverFlow, @RobertWilliams !** Please don't place your question within the code as comments, as it makes it harder to read. – Momoro May 02 '20 at 09:20
  • @Momoro, I did not find a better way – Robert Williams May 02 '20 at 09:30
  • I recommend posting the question outside of the code block, and saying something along the lines of **How do I get "THIS IS NEEDED VALUE" from HttpContext inside the** `InvokeAsync()` **method, inside of StatusCodeMiddleware?** – Momoro May 02 '20 at 09:33
  • @Momoro, I followed your advice, thanks – Robert Williams May 02 '20 at 09:39

1 Answers1

0

In order to do this you need to fiddle a little with streams. It's not pretty but if you really need to do this in a middleware you could do it like suggested in the answer here:

public async Task InvokeAsync(HttpContext httpContext)
{
    Stream originalBody = context.Response.Body;

    try
    {
        using (var memStream = new MemoryStream())
        {
            context.Response.Body = memStream;

            await next(context);

            memStream.Position = 0;
            string responseBody = new StreamReader(memStream).ReadToEnd();

            // Here responseBody == "THIS IS NEEDED VALUE"

            memStream.Position = 0;
            await memStream.CopyToAsync(originalBody);
        }
    }
    finally
    {
        context.Response.Body = originalBody;
    }
}
Xerillio
  • 4,855
  • 1
  • 17
  • 28
  • Unfortunately, it doesn't work. And so it has always been with threads in Middleware. There is exception. – Robert Williams May 02 '20 at 16:39
  • This is code: http://i.imgur.com/wLHW9k2.png. And this is exception message: http://i.imgur.com/lVtyeCq.png – Robert Williams May 02 '20 at 16:41
  • And this is my actual Startup.cs Configure method: http://i.imgur.com/ECnsDAh.png – Robert Williams May 02 '20 at 16:48
  • Okay, I changed Configure method at Startup.cs and now I get another exception. This is my new Configure method: http://i.imgur.com/Wb7cAwI.png. This is new exception: http://i.imgur.com/AwnRtaa.png – Robert Williams May 02 '20 at 16:53
  • And if i change 204 status code to 400 all is fine. I get "THIS IS NEEDED VALUE" correctly. I accept your answer at Stack Overflow. But I want to use 204 with response body. – Robert Williams May 02 '20 at 16:55
  • 1
    Okay, It stupid to write with 204 status code. I checked Wikipedia. So, great work, Xerillio, very thanks! Ha-ha, so many comments by me :). – Robert Williams May 02 '20 at 16:59
  • @RobertWilliams Haha, I was just gonna ask why you want to use 204 - there should be a more appropriate status code for you (maybe just 200?). But good to hear it's working. – Xerillio May 02 '20 at 17:00