gpt4 book ai didi

c# - Web API 审计日志记录

转载 作者:可可西里 更新时间:2023-11-01 09:16:54 26 4
gpt4 key购买 nike

我需要审核对我的 Web API 的日志调用,理想情况下我想使用一个属性,例如:

    [HttpPost, Auditing]
public dynamic MyAPICall()

属性应该能够在执行前后拦截 API 调用,以便记录参数以及 API 调用运行的时间。

使用 MVC,我可以创建一个 ActionFilterAttribute 派生并覆盖 OnActionExecuted 和 OnActionExecuting。

在 Web API 世界中是否存在等价物?

最佳答案

Http 消息处理程序应该是用于此类目的的良好可扩展点。不过要小心,并发请求内容读取可能会出现一些问题。例如,Model Binder 可能会在 LoggingHandler 读取请求内容时尝试读取请求内容,但无法反序列化模型。要防止此类问题,只需将 Wait 调用添加到 LogRequestLoggingInfo 方法。

public class LoggingHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Log the request information
LogRequestLoggingInfo(request);

// Execute the request
return base.SendAsync(request, cancellationToken).ContinueWith(task =>
{
var response = task.Result;
// Extract the response logging info then persist the information
LogResponseLoggingInfo(response);
return response;
});
}

private void LogRequestLoggingInfo(HttpRequestMessage request)
{
if (request.Content != null)
{
request.Content.ReadAsByteArrayAsync()
.ContinueWith(task =>
{
var result = Encoding.UTF8.GetString(task.Result);
// Log it somewhere
}).Wait(); // !!! Here is the fix !!!
}
}

private void LogResponseLoggingInfo(HttpResponseMessage response)
{
if (response.Content != null)
{
response.Content.ReadAsByteArrayAsync()
.ContinueWith(task =>
{
var responseMsg = Encoding.UTF8.GetString(task.Result);
// Log it somewhere
});
}
}
}

您可以阅读更多相关信息 here .

关于c# - Web API 审计日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12300458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com