4

再会。

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

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

这是该类的实现:

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 时,出现上述错误,如下所示:

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

可以做些什么来修复错误?

4

1 回答 1

12

由于您在操作过滤器中进行构造函数注入,因此您可以使用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
}
于 2018-06-19T22:41:05.783 回答