如何将 LoggerFactory 的实例传递给 ActionFilterAttribute

How can I pass an instance of LoggerFactory to ActionFilterAttribute

美好的一天。

我试图通过在我的自定义 ActionFilterAttribute 中注入 LoggerFactory 来使用日志记录 class 但是当在其中一个控制器方法中使用属性时,我收到一条错误消息

[CS7036] There is no argument given that corresponds to the required formal parameter 'logger' of 'Tracker.Tracker(ILoggerFactory)' 

下面是 class 的实现:

using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;

namespace ImmoSales.Tracking
{
    public class Tracker : ActionFilterAttribute
    {
        public string ActionType { get; set; }
        public string ActionName { get; set; }
        private readonly ILoggerFactory _logger;

        public Tracker(ILoggerFactory logger)
        {
            _logger = logger;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
        }

        public override void OnResultExecuting(ResultExecutingContext context)
        {
            base.OnResultExecuting(context);
        }

        public override void OnResultExecuted(ResultExecutedContext context)
        {
            base.OnResultExecuted(context);
        }
    }
}

当我尝试在控制器中使用跟踪器时出现上述错误,如下所示:

[Tracker(ActionType="testType", ActionName="testName")]
public IActionResult Index()
{
    return View();
}

如何解决错误?

由于您在操作过滤器中进行构造函数注入,您可以使用 ServiceFilter 属性启用它,您可以在其中传递过滤器的类型

[ServiceFilter(typeof(Tracker))]
public IActionResult Index()
{
    // to do : return something
}

确保您已在 ConfigureServices 方法中注册过滤器

services.AddScoped<Tracker>();

如果您想将其他参数传递给过滤器,您可以更新过滤器构造函数以包含这些参数。

public class Tracker : ActionFilterAttribute
{
    private string _actionType { get; set; }
    private string _actionName { get; set; }
    private readonly ILoggerFactory _logger;

    public Tracker(ILoggerFactory logger, string actionType, string actionName)
    {
        this._logger = logger;
        this._actionName = actionName;
        this._actionType = actionType;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        base.OnActionExecuting(context);
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        base.OnActionExecuted(context);
    }

    public override void OnResultExecuting(ResultExecutingContext context)
    {
        base.OnResultExecuting(context);
    }

    public override void OnResultExecuted(ResultExecutedContext context)
    {
        base.OnResultExecuted(context);
    }
}

并使用 TypeFilter 属性启用您的过滤器,您可以在其中显式传递参数

[TypeFilter(typeof(Tracker), Arguments = new object[] { "Abc", "Xyz" })]
public IActionResult Index()
{
    // to do : return something
}