ASP.NET MVC,是否可以在一个地方编写一个 Response.AppendToLog 来处理每个请求?

ASP.NET MVC, Is it possible to code a Response.AppendToLog in one place which will act on every Request?

我在本地使用 ASP.NET 4.7 和 MVC5 与 C# 和 IIS Express,并发布到 Azure 应用服务。

我想添加如下内容:

Response.AppendToLog("XXXXX Original IP = 12.12.12.12 XXXXX");

将原始 IP 地址添加到 Web 服务器日志中 "request" 列中的请求字符串。

如果我将此添加到特定的 "get" 操作,则效果很好。但是我不想将此代码添加到每个操作中。是否可以将它放在更集中的位置,以便在每个 "Get" / Request 上执行它。这可能是一个简单的问题,但目前的答案暗示了我

感谢您的智慧。

编辑:这是通过自定义操作过滤器实现的吗?

 if (filterContext.HttpContext.Request.HttpMethod=="GET")
   {
     Response.AppendToLog... //I know this will not work as Response not known.
   }

你差不多知道答案了。尝试处理 OnActionExecuted 以获得响应。

public class CustomActionFilter : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            if(filterContext.HttpContext.Request.Method == HttpMethods.Get)
            {

            }
        }

        void IActionFilter.OnActionExecuted(ActionExecutedContext context)
        {
            var response = context.HttpContext.Response;
        }
    }

我写出文本的解决方案:

filterContext.RequestContext.HttpContext.Response.AppendToLog("OrigIP");