C# 如何记录所有RESTAPI(ApiController)方法的输出?

C# 如何记录所有RESTAPI(ApiController)方法的输出?,c#,asp.net-mvc,rest,asp.net-apicontroller,C#,Asp.net Mvc,Rest,Asp.net Apicontroller,我使用C#中的APIController开发了一个RESTAPI web服务。它们将返回如下值: [System.Web.Http.HttpGet] public IHttpActionResult Index() { var maxReqLen = ConfigurationManager.AppSettings["maxRequestLength"]; return Ok(new { id = "hello" }); } 我希望将每个请求的输出记录到文件中,同时提供对HTTP请

我使用C#中的APIController开发了一个RESTAPI web服务。它们将返回如下值:

[System.Web.Http.HttpGet]
public IHttpActionResult Index()
{
   var maxReqLen = ConfigurationManager.AppSettings["maxRequestLength"];
   return Ok(new { id = "hello" });
}
我希望将每个请求的输出记录到文件中,同时提供对HTTP请求的响应


有没有办法截取输出响应并将其记录到文件中?我应该注意,我的方法有许多返回路径,我不想在使用
返回Ok(…)
的地方添加一些行,因为这会使我很容易错过一些返回。

您不必在操作中编写额外的代码行。其思想是实现一个过滤器,它将在每个请求执行后运行。然后在该过滤器中编写代码来记录输出

您要做的是创建自定义过滤器:

public class CustomAttributeName : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        HttpContext.Current.Response.Write(" Output from OnActionExecuting");
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        HttpContext.Current.Response.Write(" Output from OnActionExecuted");
    }
}
然后在
OnActionExecuted
方法中,必须将代码写入日志。 将
CustomAttributeName
添加到要记录输出的操作之上

更多详细信息可在此处找到:


下面是您编写日志的方法:

看看这篇文章:看看中间件。它在请求到达控制器之前被调用,或者在响应离开控制器但到达客户端之前被调用