Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re writing response body asp.net core custome middleware

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace DemoReact
{
    public class Middlewarecustom
    {

        private readonly RequestDelegate _next;

        public Middlewarecustom(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext context) {
            using (var buffer = new MemoryStream()) {
                var stream = context.Response.Body;
                context.Response.Body = buffer;
                await _next.Invoke(context);
                buffer.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(buffer);
                using (var bufferReader = new StreamReader(buffer)) { 
                string body = await bufferReader.ReadToEndAsync();
                    WeatherForecast wf = new WeatherForecast();
                    wf.Date = DateTime.Now;
                    wf.Summary = "demo";
                    wf.TemperatureC = 31;
                    var jsonString = JsonConvert.SerializeObject(wf);
                    byte[] bytess = Encoding.ASCII.GetBytes(jsonString);
                    var data = new MemoryStream(bytess);
                    context.Response.Body = data;
                }
            }
        }
    }
}

I have created custom middleware asp.net core to modify response body but response is blank on client side after
context.Response.Body = data; seems to not work any help on this is appreciated

like image 527
Khon Avatar asked Jun 26 '20 05:06

Khon


People also ask

How do I redirect in middleware NET Core?

Use AddRedirectToHttps to redirect HTTP requests to the same host and path using the HTTPS protocol. If the status code isn't supplied, the middleware defaults to 302 - Found. If the port isn't supplied: The middleware defaults to null .

What is IApplicationBuilder in .NET Core?

UseExceptionHandler(IApplicationBuilder) Adds a middleware to the pipeline that will catch exceptions, log them, and re-execute the request in an alternate pipeline. The request will not be re-executed if the response has already started.


1 Answers

Try like below code it might work. I have commented 3 lines and added few below that. I was stuck in similar condition and I have got it solved with multiple answers from different references. Like below links.

  1. modify middleware response
  2. Getting empty response on asp.net core middleware on exception

public async Task Invoke(HttpContext context) {
    using (var buffer = new MemoryStream()) {
        var stream = context.Response.Body;
        context.Response.Body = buffer;
        await _next.Invoke(context);
        buffer.Seek(0, SeekOrigin.Begin);
        var reader = new StreamReader(buffer);
        using (var bufferReader = new StreamReader(buffer)) { 
        string body = await bufferReader.ReadToEndAsync();
            WeatherForecast wf = new WeatherForecast();
            wf.Date = DateTime.Now;
            wf.Summary = "demo";
            wf.TemperatureC = 31;
            var jsonString = JsonConvert.SerializeObject(wf);
            
            // Commented below lines.
            // byte[] bytess = Encoding.ASCII.GetBytes(jsonString);
            // var data = new MemoryStream(bytess);
            // context.Response.Body = data;
            
            // Added new code
            await context.Response.WriteAsync(jsonString);
            context.Response.Body.Seek(0, SeekOrigin.Begin);
            
            // below code is not working with .Net 6 and it requires CopyToAsync.
            //context.Response.Body.CopyTo(stream);
            await context.Response.Body.CopyToAsync(stream); //it prevents it must be async, if it isn't there is an exception in .Net 6.
            context.Response.Body = stream;
        }
    }
}
like image 171
Karan Avatar answered Oct 28 '22 00:10

Karan