【问题标题】:How can I log output of all Rest Api(ApiController) methods?如何记录所有 Rest Api(ApiController) 方法的输出?
【发布时间】:2019-12-09 05:30:05
【问题描述】:

我在 C# 中使用 APIController 开发了一个 REST API Web 服务。它们将返回如下值:

[System.Web.Http.HttpGet]
public IHttpActionResult Index()
{
   var maxReqLen = ConfigurationManager.AppSettings["maxRequestLength"];
   return Ok(new { id = "hello" });
}

我想将每个请求的输出记录到文件中,同时我提供对 HTTP 请求的响应。

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

【问题讨论】:

  • 看看中间件。它在请求到达您的控制器之前被调用,或者在响应离开控制器之后但在到达客户端之前被调用

标签: c# asp.net-mvc rest asp.net-apicontroller


【解决方案1】:

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

你要做的是创建一个自定义过滤器:

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 添加到要记录输出的操作之上。

更多详情可以在这里找到:https://www.tutorialsteacher.com/mvc/filters-in-asp.net-mvc

您可以通过以下方式编写日志:https://stackoverflow.com/a/23660832/218408

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多