I am trying to create custom log filter in my MVC application. Following is my code
public class LoggerAttribute: ActionFilterAttribute
{
private readonly IHttpLogService _httpLogService;
private readonly ILogService _logService;
public LoggerAttribute(IHttpLogService httpLogService, ILogService logService)
{
_httpLogService = httpLogService;
_logService = logService;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
LogDetails(filterContext);
}
private void LogDetails(ActionExecutingContext filterContext)
{
try
{
HttpLogService httpService = new HttpLogService();
var httplogger = new LogMetaData()
{
RequestParams = filterContext,
ResponseParams = filterContext
};
_httpLogService.Emit("source", "", "Name", httplogger);
}
catch (Exception ex)
{
_logService.Emit("Error", "token", "Error encountered while trying to execute the request.", ex);
throw new Exception("An error occurred. Please try again later.");
}
}
}
In the above code, I was trying to pass the service instance to my filter attribute. How can I achieve passing an instance to my custom filter attribute?
Add public properties and set them in the attribute like Name property here:
Like that:
and set it: