简体   繁体   中英

c# dot net core action filter - How to read response

I have an action filter with method:

public void OnActionExecuted(ActionExecutedContext context)
    {
        try
        {
            Stream originalBody = context.HttpContext.Response.Body;
            string responseBody = string.Empty;

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

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

                    memStream.Position = 0;

                    memStream.CopyTo(originalBody);
                }

            }
            finally
            {
                context.HttpContext.Response.Body = originalBody;
            }

            _logger.LogDebug("OnActionExecuted, response=" + responseBody);

        }
        catch(Exception ex)
        {
            _logger.LogError(ex, "");
            //throw ex;
        }
        //throw new NotImplementedException();
    }

The responseBody variable is always an empty string. But I get below response on Postman:

{"custId": "1235","Channel": "InternetBanking"}

Why can't I get this on my responseBody variable?

Your problem is you create a memory stream, assign it to the Response.Body but never populate it:

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

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

    ...
}

In this code, memStream is just an empty stream so, when you read it, it reads nothing.

If you are try to access the result of the controller method then you can get hold of that via the context.Result property.

Or are you just trying to log the response body before returning the caller? Filters are not the correct place to do this - they are more concerned with the parameters into your controller method and the objects that are returned. The MVC pipeline has not populated the Response.Body so you cannnot access it - this is done by the MVC middleware.

You need to create your own custom middleware to intercept the call when the Response object has been populated and you can write that to the log. There are numerous websites that can show you how to do this. One example is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM