我希望创建一个实现 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
字典不可用。
那么,有什么方法可以在同一方法范围内访问 ActionArguments
和 Result
吗?
-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/