Str*_*ter 1 asp.net-mvc custom-action-filter actionfilterattribute asp.net-core
美好的一天。
我正在尝试通过在自定义ActionFilterAttribute类中注入LoggerFactory来使用日志记录,但是在一种控制器方法中使用Attribute时出现错误提示
[CS7036] There is no argument given that corresponds to the required formal parameter 'logger' of 'Tracker.Tracker(ILoggerFactory)'
Run Code Online (Sandbox Code Playgroud)
这是该类的实现:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在控制器中使用Tracker时,出现以下错误:
[Tracker(ActionType="testType", ActionName="testName")]
public IActionResult Index()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
如何解决该错误?
由于您要在动作过滤器中进行构造函数注入,因此可以使用ServiceFilter属性启用它,并在其中传递过滤器的类型
[ServiceFilter(typeof(Tracker))]
public IActionResult Index()
{
// to do : return something
}
Run Code Online (Sandbox Code Playgroud)
确保您已在ConfigureServices方法中注册过滤器
services.AddScoped<Tracker>();
Run Code Online (Sandbox Code Playgroud)
如果要将其他参数传递给过滤器,则可以更新过滤器构造函数以使其具有这些参数。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
并使用TypeFilter属性启用过滤器,您可以在其中显式传递参数
[TypeFilter(typeof(Tracker), Arguments = new object[] { "Abc", "Xyz" })]
public IActionResult Index()
{
// to do : return something
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
609 次 |
| 最近记录: |