c# - ASP.NET Core AsyncActionFilter 记录 ActionArguments 和结果

标签 c# asp.net-core action-filter

我希望创建一个实现 IAsyncActionFilter 的过滤器,它将从当前请求上下文的 ActionParameters 及其 Result 中检索数据。我正在使用自定义属性 MyLogAttribute 来指导日志记录行为,例如选择加入记录和指示具有关键信息的字段。

public class AsyncMyLogFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;

        if (actionDescriptor != null)
        {
            var attribute = actionDescriptor.MethodInfo.GetCustomAttribute<MyLogAttribute>();

            if (attribute != null)
            {

                await next();

                // This is where the magic is supposed to happen:
                LoggerHelper.Log(context.ActionArguments, context.Result);
            }

            return;
        }

        await next();
    }
}

过滤器提供 next() 委托(delegate)的方式让我相信,过了那个点,操作就会完成,结果对象可作为 ObjectResult 进行检查.然而,虽然过滤器能够毫无问题地获取 ActionArguments,但不幸的是 Result 属性只是 null,这根本没有帮助。

显而易见的替代方法是同步 IActionFilter,让我检查 OnActionExecuted 阶段的 Result 对象,但此时 ActionArguments 字典不可用。

那么,有什么方法可以在同一方法范围内访问 ActionArgumentsResult 吗?

-S

最佳答案

next() 的结果将是结果上下文。

此代码示例来自 Filters documentation

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;

    namespace FiltersSample.Filters
    {
        public class SampleAsyncActionFilter : IAsyncActionFilter
        {
            public async Task OnActionExecutionAsync(
                ActionExecutingContext context,
                ActionExecutionDelegate next)
            {
                // do something before the action executes
                var resultContext = await next();
                // do something after the action executes; resultContext.Result will be set
            }
        }
    }

关于c# - ASP.NET Core AsyncActionFilter 记录 ActionArguments 和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46211739/

相关文章:

c# - 启动服务未返回有关失败的足够信息

c# - 如何以编程方式构建屏幕伴侣?

c# - 在现有 Web API 中支持 ODataQueryOptions

docker - 未从dockerfile发布具有Net Core 3.1 API的Dockerfile

c# - ASP.NET Core 的 ActionFilterAttribute 中的异步 OnActionExecuting

c# - 我们如何检测 WIndows 8 中的系统音量?

c# - Azure 云存储 SDK UploadFromStreamAsync 不起作用

c# - 如何使用 C# Web 应用程序使用和重定向 JWT token URL\login\login.php?token=jwt.goes.here

c# - 在 MVC3 中的每个 Action 之前运行一个方法

asp.net-mvc - 在 Action 过滤器中实例化 View 模型?