Here is my ActionFilter:
public class LogAttribute : ActionFilterAttribute
{
public LogAttribute(ILoggerFactory logger)
{
Logger = logger.CreateLogger<LogAttribute>();
}
public string UserId { get; set; }
public string Path { get; set; }
public ILogger Logger { get; }
public override void OnActionExecuting(ActionExecutingContext context)
{
var controller = context.Controller as Controller;
UserId = User.FindFirstValue(ClaimTypes.NameIdentifier);
Path = $"{context.HttpContext.Request.Path.Value}[{context.HttpContext.Request.Method}]";
Logger.LogDebug($"{Path} started. User(id): {UserId}.");
}
}
I want to use UserId and Path properties in other places of my controllers. Is there laconic way to do it?
CodePudding user response:
If I get the question right... We're trying to pull UserId and Path (maybe query string) out of current Http Requet ?
If so, try this
public class LogAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var userId = context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier); // claims type depend on how we configure authentication. But many default fall into this constants.
var path = context.HttpContext.Request.Path;
var queryString = context.HttpContext.Request.QueryString;
//... Do whatever we need
}
}
CodePudding user response:
you can create basecontroller
public class BaseController : Controller
{
public BaseController(ILoggerFactory logger)
{
Logger = logger.CreateLogger<LogAttribute>();
}
protected string UserId { get; set; }
protected string Path { get; set; }
protected ILogger Logger { get; }
[NonAction]
public override void OnActionExecuting(ActionExecutingContext context)
{
var controllerActionDescriptor = context.ActionDescriptor as
ControllerActionDescriptor;
var controllerName = controllerActionDescriptor?.ControllerName;
var actionName = controllerActionDescriptor?.ActionName;
UserId = User.FindFirstValue(ClaimTypes.NameIdentifier);
Path = $"{context.HttpContext.Request.Path.Value}[{context.HttpContext.Request.Method}]";
Logger.LogDebug($"{Path} started. User(id): {UserId}.");
}
}