C# 如何将LoggerFactory实例传递给ActionFilterAttribute
你好 我试图通过在自定义ActionFilterAttribute类中注入LoggerFactory来使用日志记录,但在一个控制器方法中使用该属性时,我得到一个错误消息C# 如何将LoggerFactory实例传递给ActionFilterAttribute,c#,asp.net-core,actionfilterattribute,custom-action-filter,C#,Asp.net Core,Actionfilterattribute,Custom Action Filter,你好 我试图通过在自定义ActionFilterAttribute类中注入LoggerFactory来使用日志记录,但在一个控制器方法中使用该属性时,我得到一个错误消息 [CS7036] There is no argument given that corresponds to the required formal parameter 'logger' of 'Tracker.Tracker(ILoggerFactory)' 下面是该类的实现: using System; using M
[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(ActionType="testType", ActionName="testName")]
public IActionResult Index()
{
return View();
}
如何修复错误?由于您正在操作筛选器中执行构造函数注入,因此可以使用
ServiceFilter
属性启用它,您可以在该属性中传递筛选器的类型
[ServiceFilter(typeof(Tracker))]
public IActionResult Index()
{
// to do : return something
}
确保已在ConfigureServices
方法中注册筛选器
services.AddScoped<Tracker>();
并使用TypeFilter
属性启用过滤器,您可以在其中显式传递参数
[TypeFilter(typeof(Tracker), Arguments = new object[] { "Abc", "Xyz" })]
public IActionResult Index()
{
// to do : return something
}
请点击此处:
[TypeFilter(typeof(Tracker), Arguments = new object[] { "Abc", "Xyz" })]
public IActionResult Index()
{
// to do : return something
}