如何将LoggerFactory的实例传递给ActionFilterAttribute [Asp.Net核心]

时间:2018-06-19 21:25:37

标签: asp.net-mvc asp.net-core actionfilterattribute custom-action-filter

美好的一天。

我正在尝试通过在自定义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();
}

如何解决该错误?

1 个答案:

答案 0 :(得分:4)

由于要在动作过滤器中进行构造函数注入,因此可以使用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
}