Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

Modify middleware response c# .net

/// <summary>
/// The middleware Invoke method.
/// </summary>
/// <param name="httpContext">The current <see cref="HttpContext"/>.</param>
/// <returns>A Task to support async calls.</returns>
public async Task Invoke(HttpContext httpContext)
{
    var originBody = httpContext.Response.Body;
    try
    {
        var memStream = new MemoryStream();
        httpContext.Response.Body = memStream;

        await _next(httpContext).ConfigureAwait(false);

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

        //Custom logic to modify response
        responseBody = responseBody.Replace("hello", "hi", StringComparison.InvariantCultureIgnoreCase);

        var memoryStreamModified = new MemoryStream();
        var sw = new StreamWriter(memoryStreamModified);
        sw.Write(responseBody);
        sw.Flush();
        memoryStreamModified.Position = 0;

        await memoryStreamModified.CopyToAsync(originBody).ConfigureAwait(false);
    }
    finally
    {
        httpContext.Response.Body = originBody;
    }
}
Comment

Modify middleware response c# .net

public async Task Invoke(HttpContext context)
    {
        bool modifyResponse = true;
        Stream originBody = null;

        if (modifyResponse)
        {
            //uncomment this line only if you need to read context.Request.Body stream
            //context.Request.EnableRewind();

            originBody = ReplaceBody(context.Response);
        }

        await _next(context);

        if (modifyResponse)
        {
            //as we replaced the Response.Body with a MemoryStream instance before,
            //here we can read/write Response.Body
            //containing the data written by middlewares down the pipeline 

            //finally, write modified data to originBody and set it back as Response.Body value
            ReturnBody(context.Response, originBody);
        }
    }

    private Stream ReplaceBody(HttpResponse response)
    {
        var originBody = response.Body;
        response.Body = new MemoryStream();
        return originBody;
    }

    private void ReturnBody(HttpResponse response, Stream originBody)
    {
        response.Body.Seek(0, SeekOrigin.Begin);
        response.Body.CopyTo(originBody);
        response.Body = originBody;
    }
Comment

PREVIOUS NEXT
Code Example
Csharp :: Maximize Print Preview 
Csharp :: c# void with nullable List argument 
Csharp :: Last N lines from file 
Csharp :: quine in c# 
Csharp :: how to disable scale anti-aliasing in monogame 
Csharp :: isselected uicollectionview reused 
Csharp :: Auto select file in Solution Explorer from its open tab 
Csharp :: C# walk down a tree and back 
Csharp :: asp.net core relative file path within console app 
Csharp :: ienumerable tolist 
Csharp :: xamarin c# switch on hotspot Programmatically 
Csharp :: reflection static method c# 
Csharp :: .net 6 minimal api authorization net 6 
Csharp :: C# pull appart property chain in expression 
Csharp :: Get dwgexport setting reivit api 
Csharp :: sterge element din coada c# 
Csharp :: pun 2 matchmaking custom room properties 
Csharp :: c# get hwid 
Csharp :: how to split string into a list ignoring number of spaces c# 
Csharp :: how to move the camera rotation in phone in c# by touch 
Csharp :: remotefx 3d video adapter warning 
Csharp :: openiddect ef core table not creating 
Csharp :: initialization of dictionary in other forms c# 
Csharp :: switch case c# enum tostring 
Csharp :: c# text editor 
Csharp :: membership get user id 
Csharp :: convert list of object linq 
Csharp :: split string by 5 characters c# 
Csharp :: eager loading singleton c# dependency injection 
Csharp :: how to select class object from query c# 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =